在 app.config 中设置值 - 没有对程序文件的写入权限

Set value in app.config - no write access to Program Files

我想在运行时更改我的 app.config 文件(或者 MyProgramName.config 文件)中的值。使用

效果很好
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//update values in config.AppSettings...
config.Save(ConfigurationSaveMode.Modified);

但是,根据文档 (https://msdn.microsoft.com/de-de/library/system.configuration.configurationuserlevel%28v=vs.110%29.aspx)

MyProgramName.config 文件总是 存储在程序文件夹中

Application configuration files are in the same directory as the application and have the same name, but with a .config extension. For example, the configuration file for C:\System\Public.exe is C:\System\Public.exe.config.

现在假设我有一些用户无法写入 C:\Program Files(x86)\...(这是 win7 上非管理员用户的默认设置)。有没有办法继续正确使用 app.config 文件或者将它放在 %APPDATA% 文件夹中?

存储在 app.config 中的数据不适合普通用户在 运行 时更改。不要编写重写 app.config 的代码,除非此代码位于管理员的某个配置应用程序中。请改用应用程序设置。

为此,您可以使用应用程序设置的用户设置功能 api。这些设置存储在 %userprofile%\appdata\local%userprofile%\Local Settings\Application Data 中(windows 取决于版本)。

用户设置有一些限制:正如它所说,它是特定于用户的,而不是对所有用户都是全局的 - 但大概如果您在运行时更新值,那么这就是您想要的,否则您需要一些东西 like this .

您基本上只需要添加一个 .settings 文件,它会在您的 app.config 中创建 applicationSettings and/or userSettings 部分(参见 MSDN: How To: Create a New Setting at Design Time) ,创建您的 属性 并将其设置为 User,而不是 Application,然后在运行时执行此操作:

Properties.Settings.Default.myColor = Color.AliceBlue;
Properties.Settings.Default.Save();

.settings 属性 将在您的 app.config 中创建一个用户设置条目,如下所示:

<setting name="Setting1" serializeAs="String" >
 <value>My Setting Value</value>
</setting>

您可以使用它来设置在保存任何用户特定值之前用户会话将获得的默认值。

参考:MSDN: Using Application Settings and User Settings