Reputation: 527
this is my xml file...
-->
<!--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"/>
i need to edit my DailyFilName by c#. Using Key i need to change the value.
Upvotes: 1
Views: 1576
Reputation: 116
I think you want this if you are working with a app.config file
ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "C:\\App.config"};
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
config.AppSettings.Settings["SettingKey1"].Value = "newValue";
config.Save();
Upvotes: 1
Reputation: 409
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);
}
}
Upvotes: 0
Reputation: 30840
[NOTE: if you are trying to manipulate appSettings section in app.config or web.config file, use of ConfigurationManager
is recommended.]
You can do something like this :
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;
}
Usage
SetValue("DailyFilName", "...");
Upvotes: 1
Reputation: 34539
Well depending on the type of File there are a number of options you can use.
If it is a standard XML file then there are built in .NET classes you can use such as XmlReader, XmlWriter and XPathNavigator. Examples avaliable on MSDN.
If it is an app.config file then you can use the Configuration namespace to work directly with the file without the need to read/write the Xml manually. Check out the ConfigurationManager class on MSDN for some examples.
Upvotes: 3