changing configuration file at runtime

  • Thread starter Thread starter Cyrus Chiu
  • Start date Start date
C

Cyrus Chiu

I want to ask how to modify the configuration file
(windowapplication.exe.config) at runtime and keep this setting for the next
time the program start?
 
This example update app.config file (in the main project) . I think this it
will be useful to you:

Common.Utility.UpdateAppConfig("LastChange",DateTime.Now.ToString());

where

public static void UpdateAppConfig(string strKey, string strValue)

{

System.Reflection.Assembly Asm =
System.Reflection.Assembly.GetExecutingAssembly();

string strConfigLoc=Asm.Location.ToString();





string strTemp = System.IO.Path.GetDirectoryName(strConfigLoc).ToString();

System.IO.FileInfo FileInfo = new System.IO.FileInfo(strTemp + @"\" +
Asm.GetName().Name.ToString() +".exe.Config");

System.Xml.XmlDocument XmlDocument = new System.Xml.XmlDocument();

XmlDocument.Load(FileInfo.FullName);


System.Xml.XmlNodeList Nodes =
XmlDocument.DocumentElement.SelectNodes("appSettings/add[@key='"+strKey+"']"
);

if(Nodes.Count>0)

Nodes[0].Attributes.GetNamedItem("value").Value = strValue;

else

{

System.Xml.XmlElement xmlElem=XmlDocument.CreateElement("add");

XmlDocument.DocumentElement.SelectSingleNode("appSettings").AppendChild(xmlE
lem);

System.Xml.XmlAttribute XmlAttrib=XmlDocument.CreateAttribute("key");

XmlAttrib.Value =strKey;

xmlElem.Attributes.Append(XmlAttrib);

XmlAttrib=XmlDocument.CreateAttribute("value");

XmlAttrib.Value =strValue;

xmlElem.Attributes.Append(XmlAttrib);

}

XmlDocument.Save(FileInfo.FullName);

XmlDocument.Save(FileInfo.DirectoryName + @"\..\..\app.config");


}
 
Hi Cyrus,

please should consider that MS intended the configuration file not to be
changed at runtime.

You can easily write your own settings class and serialize it to XML or
whatever for that purpose.

Writing the app.config is not a good idea (although it works, I know).

Best wishes,

Neno Loje
Microsoft Student Partner
University of Hamburg
 
Hello,

Cyrus Chiu said:
I want to ask how to modify the configuration file
(windowapplication.exe.config) at runtime and keep
this setting for the next time the program start?

config files should not be modified by the application, that's why there
are no methods available for modifying them. Nevertheless, you can use
the XML classes provided by the framework to make changes to the config
files.

The config file should not be used to save user preferences. You can
use something like this instead:

http://www.palmbytes.de/content/dotnet/optionslib.htm
 
Back
Top