Method of Dynamic Change of Configuration File Information by C Programming

  • 2021-10-13 08:27:33
  • OfStack

In this paper, an example is given to describe the method of dynamically changing configuration file information by C # programming. Share it for your reference, as follows:

The configuration file is actually an XML file, so we can operate with XmlDocument.

The code is as follows:


static void Main(string[] args)
{
  XmlDocument xDoc = new XmlDocument();
  xDoc.Load("../../App.config");// Loading xml Documents 
  XmlNode xNode;
  XmlElement xElem1;
  XmlElement xElem2;
  xNode = xDoc.SelectSingleNode("//appSettings");// Gets the specified xml Child node 
  xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='type']");// Gets the specified child node in the child node 
  // If the node can be obtained, modify the node's value Value 
  if (xElem1 != null)
  {
    xElem1.SetAttribute("value", "driver");// To the value Attribute assignment ( Modification operation )
  }
  // If the node cannot be obtained, the node is created 
  else
  {
    xElem2 = xDoc.CreateElement("add");
    xElem2.SetAttribute("key", "type");
    xElem2.SetAttribute("value","teacher");
    xNode.AppendChild(xElem2);
  }
  xDoc.Save("../../App.config");// Save xml Document 
  Console.WriteLine(" Save successfully! ");
}

For more readers interested in C # related content, please check the topics on this site: "C # Common Control Usage Tutorial", "XML File Operation Skills Summary in C #", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial", "C # Object-Oriented Programming Introduction Tutorial" and "C # Programming Thread Use Skills Summary"

I hope this article is helpful to everyone's C # programming.


Related articles: