2017-08-30 89 views
2

我需要對web.config進行更改,因此我需要閱讀,直到需要進行更改的位置,進行更改,然後編寫我的更新到文件。如何從文件中讀取並在c#中更新它#

所以我們說該文件包含:

<add key="Version_PSM" value="2.2.0"/> 
<add key="Version_MLF" value="2.0.3"/> 

,我需要更新的版本PF Version_PSM爲 「2.1」。什麼是最好的方法來做到這一點?我試着打開一個FileStream,然後創建一個StreamReader和一個StreamWriter使用它,但是這不起作用。當我從文件中讀取要查找關鍵字的行時,Writer會保留在文件開頭的位置,所以當我寫入文件時它不會覆蓋我剛讀過的內容 - 它會將它寫入頂部文件。所以首先我嘗試了這樣的事情:

// Repeat in a loop until I find what I'm looking for... 
string readLine = sr.ReadLine(); 
sw.WriteLine(readline); 

它提高了作者的地位,但重複了文件中的內容。我需要定位作者覆蓋我想要更新的文本,並保持原樣。

於是,我就只是:

readLine = sr.ReadLine(); 
sw.WriteLine(); 

但只是寫入空白文件。

這裏有一個簡單的答案,我只是想念!

+1

LINQ to XML或其他XML讀/寫庫是正確的方法去這裏 – BradleyDotNET

+0

AppSettings? ConfigurationManager中? – Hackerman

+0

如果您在運行時更新web.config,請查看[此問題](https://stackoverflow.com/questions/719928/how-do-you-modify-the-web-config-appsettings-at -運行)。請注意,當您在運行時更改配置時,您的Web應用**將重新啓動。 – stuartd

回答

2

由於您需要在安裝期間更改值,因此可以使用LINQ to XML來解決您的問題(using System.Xml.Linq;)。通常,的web.config文件看起來像

<?xml version="1.0" encoding="utf-8"?> 
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> 
    <appSettings> 
    <add key="Version_PSM" value="2.2.0" /> 
    <add key="Version_MLF" value="2.0.3" /> 
    </appSettings> 
</configuration> 

您可以根據自己的名字和屬性來訪問和編輯節點。在您更改了一些值後,您可以保存更改。在以下示例中,我們正在更改Version_PSM設置的值。正如你所看到的,正確地處理命名空間在這種情況下是有點技巧的。

//Specify path 
string webConfigFile = @"\web.config"; 

//Load the document and get the default configuration namespace 
XDocument doc = XDocument.Load(webConfigFile); 
XNamespace netConfigNamespace = doc.Root.GetDefaultNamespace(); 

//Get and edit the settings 
IEnumerable<XElement> settings = doc.Descendants(netConfigNamespace + "appSettings").Elements(); 
XElement versionPsmNode = settings.FirstOrDefault(a => a.Attribute("key").Value == "Version_PSM"); 
versionPsmNode?.Attribute("value").SetValue("New value"); 

//Save the document with the correct namespace 
doc.Root.Name = netConfigNamespace + doc.Root.Name.LocalName; 
doc.Save(webConfigFile); 
+0

謝謝@Fruchtzwerg。現在我的問題是,我需要添加一個缺少的值到web.config,我無法弄清楚如何做到這一點。我正在等待:doc.Descendants(netConfigNamespace +「appsettings」)。Elements().add(KeyValuePair),但這不起作用。我怎樣才能給web.config添加一個新的值? –

+0

您需要添加一個新的'XElement'屬性到'appSettings'節點。嘗試一下類似於'doc.Root.Element(netConfigNamespace +「appSettings」)。Add(new XElement(netConfigNamespace +「add」,new XAttribute(「key」,「newKey」),new XAttribute(「value」,「newValue 「)));' – Fruchtzwerg

+0

你是天才@Fruchtzwerg!非常感謝 - 完美的作品! –

相關問題