在app.config文件中写入值

时间:2011-01-21 12:06:12

标签: c#

任何人都可以帮助我如何使用c#在app.config文件中设置/存储值,是否可以?

11 个答案:

答案 0 :(得分:40)

请尝试以下代码:

    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Add("YourKey", "YourValue");
    config.Save(ConfigurationSaveMode.Minimal);

它对我有用: - )

答案 1 :(得分:21)

在Framework 4.5上,ConfigurationManager的AppSettings.Settings [“key”]部分是只读的,因此我必须首先删除密钥,然后使用以下内容再次添加它:

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);

config.AppSettings.Settings.Remove("MySetting");
config.AppSettings.Settings.Add("MySetting", "some value");

config.Save(ConfigurationSaveMode.Modified);

请不要担心,如果您尝试删除不存在的密钥,则不会出现异常。

post提供了一些很好的建议

答案 2 :(得分:19)

private static string GetSetting(string key)
{
    return ConfigurationManager.AppSettings[key];
}

private static void SetSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save(ConfigurationSaveMode.Full, true);
    ConfigurationManager.RefreshSection("appSettings");
}

答案 3 :(得分:9)

如果您使用App.Config在<app Key="" Value="" />或CustomSections部分中存储值,请使用ConfigurationManager类,否则使用XMLDocument类。

您可以使用CodeProject

上发布的代码

答案 4 :(得分:6)

对于.NET 4.0控制台应用程序,这些都不适用于我。所以我使用下面的代码并且它起作用了:

private static void UpdateSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.
        OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save();

    ConfigurationManager.RefreshSection("appSettings");
}

答案 5 :(得分:6)

正如其他人提到的,您可以使用ConfigurationManager.AppSettings.Settings执行此操作。但: 如果密钥不存在,则使用Settings[key] = value将不起作用 使用Settings.Add(key, value),如果密钥已经存在,它会将新值连接到由逗号分隔的值,类似于 <add key="myKey" value="value1, value2, value3" />

为避免出现这些意外结果,您必须处理两个方案的

  • 如果存在具有给定密钥的条目?然后更新其值
  • 如果不存在具有给定密钥的条目?然后创建新条目(键,值)

代码

public static void Set(string key, string value)
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    var entry = config.AppSettings.Settings[key];
    if (entry == null)
        config.AppSettings.Settings.Add(key, value);
    else
        config.AppSettings.Settings[key].Value = value;

    config.Save(ConfigurationSaveMode.Modified);
}

有关支票entry == null的详情,请查看this post 希望这会对某人有所帮助。

答案 6 :(得分:3)

是的,你可以 - 见ConfigurationManager

  

ConfigurationManager类   包括使您能够使用的成员   执行以下任务:

     
      
  • 整体读写配置文件。
  •   

学会使用docs,它们应该是您第一个接听此类问题的移动电话。

答案 7 :(得分:3)

尝试以下方法:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);            
config.AppSettings.Settings[key].Value = value;
config.Save();
ConfigurationManager.RefreshSection("appSettings");

答案 8 :(得分:2)

string filePath = System.IO.Path.GetFullPath("settings.app.config");

var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
try
{
    // Open App.Config of executable
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

    // Add an Application Setting if not exist

        config.AppSettings.Settings.Add("key1", "value1");
        config.AppSettings.Settings.Add("key2", "value2");

    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);

    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");
}
catch (ConfigurationErrorsException ex)
{
    if (ex.BareMessage == "Root element is missing.")
    {
        File.Delete(filePath);
        return;
    }
    MessageBox.Show(ex.Message);
}

答案 9 :(得分:1)

//if you want change
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings[key].Value = value;

//if you want add
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add("key", value);

答案 10 :(得分:0)

我为此苦了一段时间,最后自己解决了。当时我没有找到任何帮助,但想分享我的方法。我已经做过几次,并且使用了与上面不同的方法。不确定它的坚固程度,但是对我有用。

假设您有一个名为“ txtName”的文本框,一个名为“ btnSave”的按钮,并且要保存该名称,以便下次运行程序时,键入的名称将出现在该文本框中。

  1. 转到Project> Properties>设置并创建设置-
  • name =“名称”
  • type =“ string”
  • scope =“用户”
  • 您可以留空的值。

保存您的设置文件。

  1. 转到存在文本框和按钮的表单。双击您的按钮并将此代码放入;
    //This tells your program to save the value you have to the properties file (app.config);
    //"Name" here is the name you used in your settings file above.
    Properties.Settings.Default.Name = txtName.txt;
    //This tells your program to make these settings permanent, otherwise they are only
    //saved for the current session
    Properties.Settings.Default.Save();
  1. 转到您的form_load函数并将其添加到其中;
    //This tells your program to load the setting you saved above to the textbox
    txtName.txt = Properties.Settings.Default.Name;
  1. 调试应用程序,您应该看到键入的名称。
  2. 检查应用程序调试目录,您应该会看到一个以程序命名的.config文件。用文本编辑器打开它,您将看到您的设置。

注释-

  • “名称”是指您创建的设置的实际名称。
  • 您的程序将负责创建实际的XML文件,您不必担心。