gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:55:37 26 4
gpt4 key购买 nike

我想在运行时更改我的 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% 文件夹中?

最佳答案

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

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

你基本上只需要添加一个 .settings 文件,它在你的 app.config 中创建 applicationSettings 和/或 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>

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

引用:MSDN: Using Application Settings and User Settings

关于c# - 在 app.config 中设置值 - 没有对程序文件的写入权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32136253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com