2010-11-23 124 views
1

,這是我的xml文件...編輯XML文件C#

- >

<!--Daily Genarated File Path--> 
<add key="DailyFilName" value="C:\DailySummary.xls"/> 
<!--Weekly Genarated File Path--> 
<add key="WeeklyFilName" value="C:\WeeklySummary.xls"/> 
<!--Log File Path--> 
<add key="LogFilName" value="c:\\TranmittalsLog.txt"/> 

我需要通過c#編輯我的DailyFilName。使用密鑰我需要更改值。

+0

是這個App.config文件? – Shekhar 2010-11-23 09:13:33

回答

3

那麼取決於文件的類型,您可以使用多種選項。

如果它是一個標準的XML文件,那麼你可以使用.NET類,如XmlReader,XmlWriterXPathNavigator。在MSDN上可用的示例。

如果它是一個app.config文件,那麼您可以使用Configuration命名空間直接使用該文件而不需要手動讀取/寫入Xml。有關示例,請參閱MSDN上的ConfigurationManager類。

1

[注意:如果你試圖操縱的app.config或web.config文件appSettings部分,建議使用的ConfigurationManager]

你可以做這樣的事情:

private void SetValue(String key, String value) 
    { 
     XDocument doc = XDocument.Load("..."); 
     XElement element = doc.Descendants("add").Where(d => d.Attribute("key") != null && d.Attribute("key").Value == key).First(); 
     element.Attribute("value").Value = value; 
    } 

用法

SetValue("DailyFilName", "..."); 
0
private void SetValue(string xmlFilePath, string key, string value) 
{ 
    try 
    { 
     XDocument doc = XDocument.Load(xmlFilePath); 
     XElement element = doc.Descendants("add").Where(d => d.Attribute("key") != null && d.Attribute("key").Value == key).First(); 
     element.Attribute("value").Value = value; 
     doc.Save(xmlFilePath); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
} 
1

我想你想這個,如果您使用的是應用程序的工作。配置文件

ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "C:\\App.config"}; 

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); 

config.AppSettings.Settings["SettingKey1"].Value = "newValue"; 
config.Save();