更新配置文件

Update config file

我在使用 C# 更新 VS2013 中的 ConfigFile 时遇到问题。 我有这个代码:

Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection confCollection = configManager.AppSettings.Settings;

confCollection["ID_Uzivatele"].Value = ID_Uzivatele;

configManager.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name); 

(ID_Uzivatele 是一个字符串变量)

和配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ID_Uzivatele" value="default"/>
  </appSettings>
</configuration>

我的问题是(错误列表): 'System.NullReferenceException' 类型的未处理异常发生在 KomunikacniAplikace.exe

有人知道我做错了什么吗?

我建议查看未设置设置的错误案例:这对我有用:

(假设字符串有一个 const,这样您就不会输入错误...)

const string ID_UZIVATELE = "ID_Uzivatele";

主要代码:

    Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    KeyValueConfigurationCollection confCollection = configManager.AppSettings.Settings;

    if (confCollection.AllKeys.Contains(ID_UZIVATELE)) {
        Console.Out.WriteLine("Contains key, modifying : was " + confCollection["ID_Uzivatele"].Value);
        confCollection["ID_Uzivatele"].Value = "foo";

    } else {
        Console.Out.WriteLine("Doesn't contain key, adding");
        confCollection.Add(ID_UZIVATELE, "Boom");
    }

    configManager.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name);

如果配置文件丢失,这将生成它(您可能想检查您的 App.Config 是否确实被复制到输出文件夹(这可能是错误的根本原因),但是建立针对不良配置的保护总是有帮助的。