ConfigurationManager.AppSettings - 如何修改和保存?

发布于 2024-10-21 07:41:36 字数 874 浏览 3 评论 0原文

这听起来可能太简单了,我按照文章中的建议做了同样的事情,但它并没有按预期工作。希望有人能指出我正确的方向。

我想保存每个 AppSettings 的用户设置。

一旦 Winform 关闭,我就会触发此操作:

conf.Configuration config = 
           ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

if (ConfigurationManager.AppSettings["IntegrateWithPerforce"] != null)
    ConfigurationManager.AppSettings["IntegrateWithPerforce"] = 
                                           e.Payload.IntegrateCheckBox.ToString();
else
    config.AppSettings.Settings.Add("IntegrateWithPerforce", 
                                          e.Payload.IntegrateCheckBox.ToString());

config.Save(ConfigurationSaveMode.Modified);

因此,第一次当该条目尚不存在时,它只会创建它,否则它将修改现有条目。但这并不能保存。

1)我做错了什么?

2) 我期望应用程序设置的用户设置再次保存在哪里?是在 Debug 文件夹中还是在 C:\Documents and Settings\USERNAME\Local Settings\Application Data 文件夹中?

It might sound too trival to ask and I do the same thing as suggested in articles, yet it doesn't work as expected. Hope someone can point me to the right direction.

I would like to save the usersettings per AppSettings.

Once the Winform is closed I trigger this:

conf.Configuration config = 
           ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

if (ConfigurationManager.AppSettings["IntegrateWithPerforce"] != null)
    ConfigurationManager.AppSettings["IntegrateWithPerforce"] = 
                                           e.Payload.IntegrateCheckBox.ToString();
else
    config.AppSettings.Settings.Add("IntegrateWithPerforce", 
                                          e.Payload.IntegrateCheckBox.ToString());

config.Save(ConfigurationSaveMode.Modified);

So the first time when the entry doesnt exist yet, it would simply create it, otherwise it would modify the existing entry. However this doesn't save.

1) What am I doing wrong?

2) Where am I expecting the usersettings for App settings to be saved again? Is it in the Debug folder or in C:\Documents and Settings\USERNAME\Local Settings\Application Data folder?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

女中豪杰 2024-10-28 07:41:36

我知道我迟到了:)但这就是我的做法:

public static void AddOrUpdateAppSettings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

有关详细信息,请参阅 MSDN

I know I'm late :) But this how i do it:

public static void AddOrUpdateAppSettings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

For more information look at MSDN

梦太阳 2024-10-28 07:41:36

关于如何更改 app.config 文件中 appSettings 部分的值:

config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);

完成这项工作。

当然更好的做法是设置类,但这取决于你想要什么。

On how to change values in appSettings section in your app.config file:

config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);

does the job.

Of course better practice is Settings class but it depends on what are you after.

忘年祭陌 2024-10-28 07:41:36

优先选择 而非 部分。使用 (Web)ConfigurationManager 读取和写入要容易得多。 ConfigurationSection、ConfigurationElement 和 ConfigurationElementCollection 要求您派生自定义类并实现自定义 ConfigurationProperty 属性。在我看来,对于普通人来说太多了。

以下是读取和写入 web.config 的示例:

using System.Web.Configuration;
using System.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
string oldValue = config.AppSettings.Settings["SomeKey"].Value;
config.AppSettings.Settings["SomeKey"].Value = "NewValue";
config.Save(ConfigurationSaveMode.Modified);

之前:

<appSettings>
  <add key="SomeKey" value="oldValue" />
</appSettings>

之后:

<appSettings>
  <add key="SomeKey" value="newValue" />
</appSettings>

Prefer <appSettings> to <customUserSetting> section. It is much easier to read AND write with (Web)ConfigurationManager. ConfigurationSection, ConfigurationElement and ConfigurationElementCollection require you to derive custom classes and implement custom ConfigurationProperty properties. Way too much for mere everyday mortals IMO.

Here is an example of reading and writing to web.config:

using System.Web.Configuration;
using System.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
string oldValue = config.AppSettings.Settings["SomeKey"].Value;
config.AppSettings.Settings["SomeKey"].Value = "NewValue";
config.Save(ConfigurationSaveMode.Modified);

Before:

<appSettings>
  <add key="SomeKey" value="oldValue" />
</appSettings>

After:

<appSettings>
  <add key="SomeKey" value="newValue" />
</appSettings>
玩世 2024-10-28 07:41:36

也许您应该考虑添加一个设置文件。 (例如应用程序设置)
创建此文件将允许您执行以下操作:

string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";

这意味着您可以编辑然后更改项目,其中项目是强类型的,最重要的是...您不必在部署之前接触任何 xml!

结果是应用程序或用户上下文设置。

查看“添加新项目”菜单中的设置文件。

Perhaps you should look at adding a Settings File. (e.g. App.Settings)
Creating this file will allow you to do the following:

string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";

This means you can edit and then change items, where the items are strongly typed, and best of all... you don't have to touch any xml before you deploy!

The result is a Application or User contextual setting.

Have a look in the "add new item" menu for the setting file.

﹉夏雨初晴づ 2024-10-28 07:41:36

由于基本问题是关于 win 表单,因此解决方案如下:
(我刚刚通过 user1032413 更改了代码以 rflect windowsForms 设置)
如果它是新密钥:

Configuration config = configurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings.Add("Key","Value");
config.Save(ConfigurationSaveMode.Modified);

如果该密钥已经存在:

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings["Key"].Value="Value";
config.Save(ConfigurationSaveMode.Modified);

as the base question is about win forms here is the solution :
( I just changed the code by user1032413 to rflect windowsForms settings )
if it's a new key :

Configuration config = configurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings.Add("Key","Value");
config.Save(ConfigurationSaveMode.Modified);

if the key already exists :

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings["Key"].Value="Value";
config.Save(ConfigurationSaveMode.Modified);
冷心人i 2024-10-28 07:41:36

尝试在保存调用后添加此内容。

ConfigurationManager.RefreshSection( "appSettings" );

Try adding this after your save call.

ConfigurationManager.RefreshSection( "appSettings" );
舟遥客 2024-10-28 07:41:36

请记住,ConfigurationManager 仅使用一个 app.config - 启动项目中的一个。

如果您将一些 app.config 放入解决方案 A 并从另一个解决方案 B 引用它,那么如果您运行 B,则 A 中的 app.config 将被忽略。

因此,例如单元测试项目应该有自己的app.config。

Remember that ConfigurationManager uses only one app.config - one that is in startup project.

If you put some app.config to a solution A and make a reference to it from another solution B then if you run B, app.config from A will be ignored.

So for example unit test project should have their own app.config.

财迷小姐 2024-10-28 07:41:36

我认为问题是在调试 Visual Studio 中不使用正常的 exeName。

它使用indtead“NameApplication”.host.exe,

因此配置文件的名称是“NameApplication”.host.exe.config而不是
“NameApplication”.exe.config

并在应用程序关闭后 - 它返回到后面的 app.config,

因此如果您检查错误的文件或检查错误的时间,您将看到没有任何变化。

I think the problem is that in the debug visual studio don't use the normal exeName.

it use indtead "NameApplication".host.exe

so the name of the config file is "NameApplication".host.exe.config and not
"NameApplication".exe.config

and after the application close - it return to the back app.config

so if you check the wrong file or you check on the wrong time you will see that nothing changed.

虫児飞 2024-10-28 07:41:36

我已经记录了一个有效的解决方案,用于存储、检索和更新 .NET 8 控制台应用程序的设置以与 IP 服务通信,即 IP 地址和端口。它包括验证检索到的值Save_retrieve_and_validate_IpAddress_and_Port

I've documented a worked solution for storing, retrieving and updating a .NET 8 Console apps' settings for communicating with an IP Service, namely IPaddress and Port. It includes validation of the retrieved values Save_retrieve_and_validate_IpAddress_and_Port

凉栀 2024-10-28 07:41:36

您可以手动更改它:

private void UpdateConfigFile(string appConfigPath, string key, string value)
{
     var appConfigContent = File.ReadAllText(appConfigPath);
     var searchedString = $"<add key=\"{key}\" value=\"";
     var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
     var currentValue = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
     var newContent = appConfigContent.Replace($"{searchedString}{currentValue}\"", $"{searchedString}{newValue}\"");
     File.WriteAllText(appConfigPath, newContent);
}

You can change it manually:

private void UpdateConfigFile(string appConfigPath, string key, string value)
{
     var appConfigContent = File.ReadAllText(appConfigPath);
     var searchedString = $"<add key=\"{key}\" value=\"";
     var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
     var currentValue = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
     var newContent = appConfigContent.Replace($"{searchedString}{currentValue}\"", $"{searchedString}{newValue}\"");
     File.WriteAllText(appConfigPath, newContent);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文