我在使用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是一个String变量)
和configFile
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ID_Uzivatele" value="default"/>
</appSettings>
</configuration>
我的问题是(错误列表): KomunikacniAplikace.exe中出现未处理的“System.NullReferenceException”类型异常
任何人都知道我做错了什么?
答案 0 :(得分:0)
我建议查看设置未设置的错误情况:这对我有用:
(假设这是字符串的常量,所以你不会得到错字......)
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实际上是否被复制到输出文件夹(这可能是您的错误的根本原因),但建立防止坏的保护配置总是很有用。