使用LINQ更新app.config

时间:2012-07-09 14:59:41

标签: c# xml linq linq-to-xml app-config

我有一个app.config文件。

我想要检索和编辑属性:

<appSettings>
    <add key="ProcessorInstances" value="2" />
</appSettings>

我正在使用此查询:

var list5 = from appNode in doc2.Descendants("appSettings").Elements() 
            where appNode.Attribute("key").Value == "ProcessorInstances" 
            select appNode;
var element5 = list5.FirstOrDefault();
string five = element5.Attribute("value").Value; 

但现在我面临着像:

这样的元素
<app>
    <file value="../../../logs/Intel.Service.log" />
</app>

<baseAddresses>
    <add baseAddress="http://Machinename:portnumber/servicename/" />
</baseAddresses>

这些元素没有任何关键属性。

如何编写LINQ查询来编辑它们?

1 个答案:

答案 0 :(得分:7)

将app.Config文件解析为xml并使用Linq不是从App.Config获取设置的方法。而是使用 System.Configuration.ddl (在项目中添加对此文件的引用)。

E.g。

string baseAddress = ConfigurationManager.AppSettings["baseAddress"].ToString();