writing config-file

  • Thread starter Thread starter MK
  • Start date Start date
M

MK

Is there any way to write into the app config at runtime?

I want to store position, height and width of my forms.
 
This code should do:

// use reflection to find the location of the config file
System.Reflection.Assembly asm =
System.Reflection.Assembly.GetExecutingAssembly ();
System.IO.FileInfo fi = new System.IO.FileInfo
(String.Format ("{0}.config", asm.Location));
if (!fi.Exists)
throw new Exception ("Missing config file");

// load the config file into the XML DOM.
System.Xml.XmlDocument xmlConfig = new System.Xml.XmlDocument
();
xmlConfig.PreserveWhitespace = true;
xmlConfig.Load (fi.FullName);

// find the right node and change it to the new value
foreach (System.Xml.XmlNode node in
xmlConfig["configuration"]["appSettings"])
{
if ((node.Name == "add") &&
(node.Attributes.GetNamedItem ("key").Value ==
"Height"))
{
node.Attributes.GetNamedItem ("value").Value =
newHeight;
}
< similar blocks for other parameters >
}

// write out the new config file
xmlConfig.Save (fi.FullName);

Eliyahu
 
Eliyahu,

Thanks for the code sample. I am pretty new at this but why did you use:

System.Reflection.Assembly asm =
System.Reflection.Assembly.GetExecutingAssembly ();
System.IO.FileInfo fi = new System.IO.FileInfo
(String.Format ("{0}.config", asm.Location));

rather than:


AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE")

thanks,

dlr

Eliyahu Goldin said:
This code should do:

// use reflection to find the location of the config file
System.Reflection.Assembly asm =
System.Reflection.Assembly.GetExecutingAssembly ();
System.IO.FileInfo fi = new System.IO.FileInfo
(String.Format ("{0}.config", asm.Location));
if (!fi.Exists)
throw new Exception ("Missing config file");

// load the config file into the XML DOM.
System.Xml.XmlDocument xmlConfig = new System.Xml.XmlDocument
();
xmlConfig.PreserveWhitespace = true;
xmlConfig.Load (fi.FullName);

// find the right node and change it to the new value
foreach (System.Xml.XmlNode node in
xmlConfig["configuration"]["appSettings"])
{
if ((node.Name == "add") &&
(node.Attributes.GetNamedItem ("key").Value ==
"Height"))
{
node.Attributes.GetNamedItem ("value").Value =
newHeight;
}
< similar blocks for other parameters >
}

// write out the new config file
xmlConfig.Save (fi.FullName);

Eliyahu

MK said:
Is there any way to write into the app config at runtime?

I want to store position, height and width of my forms.
 
Back
Top