0 Comments

The following code shows how to serialize and deserialize an object in C# to a XML file.

 

Code

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;

namespace MobileUI.BC
{
    public class SerializationHelper<T> where T : class, new()
    {
        private string _fileName;
        public string FileName
        {
            get
            {
                if (string.IsNullOrEmpty(_fileName))
                {
                    _fileName = "Data.xml";
                }
                return _fileName;
            }
            set
            {
                _fileName = value;
            }
        }
        private T _data;
        public T Data
        {
            get
            {
                if (_data == null)
                {
                    _data = new T();
                }
                return _data;
            }
            set
            {
                _data = value;
            }
        }

        public void Save()
        {
            string filePath = Path.Combine(GetExecutionPath(), FileName);
            
            using (TextWriter writer = new StreamWriter(filePath))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                xs.Serialize(writer, this.Data);
            }

        }
        public T Load()
        {
            string filePath = Path.Combine(GetExecutionPath(), FileName);

            using (TextReader reader = new StreamReader(filePath))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                this.Data = xs.Deserialize(reader) as T;
            }

            return this.Data;
        }
        public static string GetExecutionPath()
        {
            string codeBase = Assembly.GetExecutingAssembly().GetName().CodeBase;
            return new Uri(Path.GetDirectoryName(codeBase)).LocalPath;
        }
    }
}

 

Example

        [TestMethod]
        public void SaveTest()
        {
            Data data = new Data();
            data.Days = 2;

            SerializationHelper<Data> sh = new SerializationHelper<Data>();
            sh.Data = data;
            sh.Save();
            
            data.Days = 3;
            data = sh.Load();

            Console.WriteLine(data.Days);
        }

 

Result

2

One Reply to “How to serialize and deserialize an object in C# to a XML file”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts