Write class instance to XML File and read file contents

You have a class and you need to save values to of the class to an xml file to be consumed later on 

  public  class TemplateInformation
        public string StoredProcedure { get; set; }
        public List<string> Parameters { get; set; }
        public string TemplatePath { get; set; }
        public string TemplateName { get; set; }
        public String Title { get; set; }

       public TemplateInformation()
            Parameters  = new List<string>();


Save your class values to

  public bool SaveTemplate()

            var report = new TemplateInformation
                StoredProcedure = "ReadReportData",
                TemplateName = "Report.xls",
                TemplatePath = @"c:\templates",
                Title = "Monthly Income Report"

            XmlSerializer xs = new XmlSerializer(typeof(TemplateInformation));
            TextWriter tw = new StreamWriter(@"c:\Temp\TemplateInformation.xml");
            xs.Serialize(tw, report);
            return true;


This is the template content

<TemplateInformation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Title>Monthly Income Report</Title>

To read the content of the xml back to your class

 public TemplateInformation ReadTemplate()
            TemplateInformation report;
            string templateName = @"c:\Temp\TemplateInformation.xml";

            XmlSerializer xs = new XmlSerializer(typeof(TemplateInformation));
            using (var sr = new StreamReader(templateName))
                report = (TemplateInformation)xs.Deserialize(sr);
           return report;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s