我已经使用Configuration Section Designer(csd)为我的应用程序生成xml配置文件。
现在,我想使用这个xml文件(在c#上)并做两件事:
1。读取特定值(按字段搜索),例如
txtbox_username.Text = ConfigurationManager.AppSettings["userName"];
2。写一个特定的值,比如
config.AppSettings.Settings["userName"].Value = txtbox_username.Text;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("configuration");
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
add key="userName" value="Value1"
</appSettings>
</configuration>
但是csd生成的xml看起来不同......
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="sectionName" type="Sample.ConfigurationSection.sectionName, Sample.ConfigurationSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>
<sectionName xmlns="Sample.ConfigurationSection">
<logFile debugLevel="3" filePath="c:\new" maxFileCount="10" maxFileLength="1000"/>
<results path="C:\Results"/>
<details user="blabla" pass="12345" code="abc"/>
<stuff fromAddress="from@gmail.com" toAddress="to@gmail.com" sendMail="true""/>
</sectionName>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
在这里,我想编辑和保存,例如,用户/通行证/代码字段。
答案 0 :(得分:0)
简而言之(并使用这些扩展名:http://searisen.com/xmllib/extensions.wiki)你可以这样做来读/写用户,
XElement file = XElement.Load(xmlFile);
XNamespace ns = "Sample.ConfigurationSection";
XElement section = file.GetElement(ns + "sectionName");
string user = section.Get("details/user", string.Empty);
section.Set("details/user", "bubba", true); // true = set as attribute
file.Save(xmlFile);