将值添加到app.config并检索它们

dev*_*ull 72 c#

我需要在app.Config中插入键值对,如下所示:

<configuration>
 <appSettings>
    <add key="Setting1" value="Value1" />
    <add key="Setting2" value="Value2" />
 </appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

当我在谷歌搜索时,我得到以下代码片段

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Add an Application Setting.

config.AppSettings.Settings.Add("ModificationDate",
               DateTime.Now.ToLongTimeString() + " ");

// Save the changes in App.config file.

config.Save(ConfigurationSaveMode.Modified);
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,因为System.Configuration命名空间中找不到ConfigurationManager我正在使用.NET 2.0.如何以编程方式将键值对添加到app.Config并检索它们?

Arj*_*nbu 52

您是否缺少对System.Configuration.dll的引用?ConfigurationManager上课就在那里.

编辑:System.Configuration命名空间在mscorlib.dll,system.dll和system.configuration.dll中有类.您的项目始终包含mscorlib.dll和system.dll引用,但必须将system.configuration.dll添加到大多数项目类型中,因为默认情况下它不存在...

  • 这有时让我感到高兴!我一直认为我需要的只是一个使用:( (2认同)

小智 11

这有效.

public static void AddValue(string key, string value)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Add(key, value);
    config.Save(ConfigurationSaveMode.Minimal);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你想能够访问这个值,你稍后在代码中添加而不重新启动应用程序,则需要调用`ConfigurationManager.RefreshSection("appSettings");`之后. (3认同)

One*_*HOT 9

尝试添加一个引用System.Configuration,通过引用System命名空间获得一些配置命名空间,添加对System.Configuration的引用应该允许您访问ConfigurationManager.


Sur*_*raj 5

我希望这有效:

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

config.AppSettings.Settings["Yourkey"].Value = "YourValue";
config.Save(ConfigurationSaveMode.Modified);
Run Code Online (Sandbox Code Playgroud)