locked
Xml Configuration File read write using C# RRS feed

  • Question

  • Hello,

    I want to read and write xml configuration file using C#. Can anybody help me out.

    XmlReader is not able to use,as configuration file has little different structure than pure xml file.

    Tuesday, July 31, 2012 9:34 AM

Answers

  • Hi lovelyCSharp,

    If you are trying to read an Application Config file,then I suggest you to use the "ConfigurationManager" class found in the System.Configuration class.

    This way you can read the file better.

    HTH.!


    Thanks, Satish Bommideni "Success usually comes to those who are too busy to be looking for it."

    Tuesday, July 31, 2012 11:49 AM
  • You can use the XmlSerializer class like this:

    public class MyConfig
    {
       public string property1;
       public string property2; 
    }
    
    ...
    
    // Create an instance of the XmlSerializer class;
    // specify the type of object to serialize.
      XmlSerializer serializer = 
        new XmlSerializer(typeof(MyConfig));
    
      MyConfig config = new MyConfig();
      config.property1 = "option1";
      config.property2 = "option2";
    
      using (TextWriter writer = new StreamWriter(filename))
      {
        serializer.Serialize(writer, config);
      }
    

    To deserialize:

    using (FileStream fs = new FileStream(filename, FileMode.Open))
    {
      MyConfig config = (MyConfig)serializer.Deserialize(fs);
    }
    
    //important: either wrap Streams with using statements 
    //or do a fs.Close() when done.

    Dan Randolph - My Code Samples List

    Wednesday, August 1, 2012 4:28 AM

All replies

  • Hi lovelyCSharp,

    If you are trying to read an Application Config file,then I suggest you to use the "ConfigurationManager" class found in the System.Configuration class.

    This way you can read the file better.

    HTH.!


    Thanks, Satish Bommideni "Success usually comes to those who are too busy to be looking for it."

    Tuesday, July 31, 2012 11:49 AM
  • You can use the XmlSerializer class like this:

    public class MyConfig
    {
       public string property1;
       public string property2; 
    }
    
    ...
    
    // Create an instance of the XmlSerializer class;
    // specify the type of object to serialize.
      XmlSerializer serializer = 
        new XmlSerializer(typeof(MyConfig));
    
      MyConfig config = new MyConfig();
      config.property1 = "option1";
      config.property2 = "option2";
    
      using (TextWriter writer = new StreamWriter(filename))
      {
        serializer.Serialize(writer, config);
      }
    

    To deserialize:

    using (FileStream fs = new FileStream(filename, FileMode.Open))
    {
      MyConfig config = (MyConfig)serializer.Deserialize(fs);
    }
    
    //important: either wrap Streams with using statements 
    //or do a fs.Close() when done.

    Dan Randolph - My Code Samples List

    Wednesday, August 1, 2012 4:28 AM