更新配置文件
本文关键字:配置文件 更新 | 更新日期: 2023-09-27 18:09:17
我在VS2013中用c#更新我的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是一个字符串变量)
和configFile
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ID_Uzivatele" value="default"/>
</appSettings>
</configuration>
我的问题是(错误列表):未处理的System类型异常。
在komunikacniapplikace .exe中发生NullReferenceException 有人知道我做错了什么吗?我建议查看未设置的错误情况:这对我有效:
(假设字符串有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是否实际上被复制到输出文件夹(这可能是你错误的根本原因),但是构建防止错误配置的保护总是有用的。