Hi,
I am developing a Window Application in VS2008.
Can anyone tell me how to write /modify the app.config value
programmatic-ally for a specific key ?
I have tried searching the internet but getting solutions for Web
application not for Window Application.
Thanks in Advance for kind help.
Loading
Ankur GuptaPosted May 26, 2010, 6:55 AM
public static void WriteSetting(string key, string value)
{
////load config document for current assembly
XmlDocument doc = loadConfigDocument();
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new InvalidOperationException("appSettings section not found in config file.");
}
try
{
// select the 'add' element that contains the key
XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
if (elem != null)
{
// add value for key
elem.SetAttribute("value", value);
}
else
{
// key was not found so create the 'add' element
// and set it's key/value attributes
elem = doc.CreateElement("add");
elem.SetAttribute("key", key);
elem.SetAttribute("value", value);
node.AppendChild(elem);
}
doc.Save(getConfigFilePath());
}
catch
{
throw;
}
}
public static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
}
public static string getConfigFilePath()
{
return Assembly.GetExecutingAssembly().Location + ".config";
}
Also you can read my artical on this site about all of this.
Ankur GuptaPosted May 26, 2010, 6:53 AM
public static void SaveSetting(string ConnectionString1)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove("SqlConnectionADODB");
config.AppSettings.Settings.Add("SqlConnectionADODB", ConnectionString1);
config.Save();
ConfigurationManager.RefreshSection("appSettings");
}
CrishPosted May 15, 2010, 5:29 AM
You can edit windows App.config file. hope below link give your solution.
http://www.codeproject.com/KB/cs/SystemConfiguration.aspx
thanks
Don't forget to Mark Do you like this Answer that solved your problem!