配置管理器。应用程序设置-如何修改和保存?

这个问题听起来可能太琐碎了,我做了文章中建议的同样的事情,但是它并不像预期的那样工作。希望有人能给我指明正确的方向。

我想保存每个应用程序设置的用户设置。

一旦信息通道关闭,我就会触发这个:

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)我希望应用程序设置的用户设置在哪里再次保存?是在“调试”文件夹中还是在“ C: 文档和设置 USERNAME 本地设置应用程序数据”文件夹中?

254513 次浏览

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.

Try adding this after your save call.

ConfigurationManager.RefreshSection( "appSettings" );

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.

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>

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.

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 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

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.

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);
}