2010-11-23 121 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();