我對C#比較陌生,剛開始使用XmlElement和SingleNode方法。出於某種原因,「customSettings」保持返回null,儘管正在加載XML文檔。我已經通過加載它作爲一個字符串來檢查。我已經嘗試了迄今爲止我能想象到的一切,包括評論中的嘗試。任何幫助或建議非常感謝。這是我的XML文檔:C#XmlElement:爲什麼總是返回Nulll?
編輯:從CodingYoshi解決方案,但有沒有更好的方法?
編輯:改變XML和代碼NSGaga解決user.config與NameValueCollection中讀取唯一的例外
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="users_fächer" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<users_faecher>
<add key="user1" value="value1" />
<add key="user2" value="value2" />
</users_faecher>
</configuration>
代碼:
string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Users.config");
string new_fächer = input[1];
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = dir;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
ConfigurationSection myParamsSection = config.GetSection("users_faecher");
string myParamsSectionRawXml = myParamsSection.SectionInformation.GetRawXml();
XmlDocument sectionXmlDoc = new XmlDocument();
sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml));
NameValueSectionHandler handler = new NameValueSectionHandler();
NameValueCollection users_fächer = handler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection;
users_fächer.Set(user, new_fächer);
config.Save(ConfigurationSaveMode.Modified, true);
尼古拉你可以發佈一個小控制檯項目 - 'VAR customSettings = ConfigurationManager.GetSection( 「數據/ faecher」)作爲NameValueCollection中;'不應該返回null,一切是正確的存在。而且你不應該像XML那樣加載配置文件,因爲它非常糟糕:)。這裏還有其他一些問題,我只是不確定你在做什麼。因此,剝離所有其他東西只是配置,因爲你有它,並且一行 – NSGaga
@NSGaga發現打開該部分的問題,但是當我嘗試在NameValueCollection上設置方法它告訴我它的只讀,雖然它的自定義用戶.config而不是一個app.config。我編輯了代碼和xml數據讓你看到我現在得到了什麼 – Nikolas
@NSGaga現在都編輯了,你有什麼線索爲什麼它不讓我編輯? – Nikolas