Friday, 4 January 2013

Serialize and Deserialize class into xml and vire-versa in C#


using System.Text;
using System.IO;
using System.Xml.Serialization;


[Serializable]
    public class UIDatabaseInfo
    {
        #region "-- Properties --"

        private string _DatabaseName = string.Empty;
        public string DatabaseName
        {
            get { return _DatabaseName; }
            set { _DatabaseName = value; }
        }

        private string _DatabaseFilename = string.Empty;
        public string DatabaseFilename
        {
            get { return _DatabaseFilename; }
            set { _DatabaseFilename = value; }
        }

        private string _LastModifiedDataNTime = string.Empty;
        public string LastModifiedDataNTime
        {
            get { return _LastModifiedDataNTime; }
            set { _LastModifiedDataNTime = value; }
        }

        private bool _IsXmlFilesGenerated = false;
        public bool IsXmlFilesGenerated
        {
            get { return _IsXmlFilesGenerated; }
            set { _IsXmlFilesGenerated = value; }
        }

        #endregion
    }
[Serializable]
    public class UIDatabaseDetails
    {
        #region "-- Properties --"

        private List<UIDatabaseInfo> _DatabaseInfo = new List<UIDatabaseInfo>();
        public List<UIDatabaseInfo> DatabaseInfo
        {
            get { return _DatabaseInfo; }
            set { _DatabaseInfo = value; }
        }

        #endregion

        #region "-- Public --"

        #region "-- Methods --"

        /// <summary>
        /// Save serialize data into xml file
        /// </summary>
        /// <param name="xmlFileWithPath"></param>
        public void Save(string xmlFileWithPath)
        {
            FileStream FS = null;
            XmlSerializer SRZFrmt;

            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(xmlFileWithPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(xmlFileWithPath));
                }

                FS = new FileStream(xmlFileWithPath, FileMode.Create);
                SRZFrmt = new XmlSerializer(typeof(UIDatabaseDetails));
                SRZFrmt.Serialize(FS, this);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (FS != null)
                {
                    FS.Flush();
                    FS.Close();
                }
            }
        }

        /// <summary>
        /// Load xml file and deserialize data
        /// </summary>
        /// <param name="xmlFileWithPath"></param>
        /// <returns></returns>
        public UIDatabaseDetails Load(string xmlFileWithPath)
        {
            UIDatabaseDetails RetVal = new UIDatabaseDetails();
            string FilePath = string.Empty;
            FileStream FS = null;

            try
            {
                if (!File.Exists(xmlFileWithPath))
                {
                    FilePath = Path.GetDirectoryName(xmlFileWithPath);

                    if (!Directory.Exists(FilePath))
                    {
                        Directory.CreateDirectory(FilePath);
                    }

                    (new UIDatabaseDetails()).Save(xmlFileWithPath);
                }

                FS = new FileStream(xmlFileWithPath, FileMode.Open);
                XmlSerializer Serializer = new XmlSerializer(typeof(UIDatabaseDetails));
                RetVal = (UIDatabaseDetails)Serializer.Deserialize(FS);
            }
            catch (Exception)
            {
            }
            finally
            {
                if (FS != null)
                {
                    FS.Flush();
                    FS.Close();
                }
            }

            return RetVal;
        }

        #endregion

        #endregion
    }



Ex. Code:
UIDatabaseDetails UIDbDetails = null;
string DbDetailsXmlFileWithPath = string.Empty;
UIDatabaseInfo CurrentDBInfo = null;

//-- Load current database details from xml file
UIDbDetails = new UIDatabaseDetails();
UIDbDetails = UIDbDetails.Load(DbDetailsXmlFileWithPath);

//-- Create current database info
CurrentDBInfo = new UIDatabaseInfo();
CurrentDBInfo.DatabaseName = "ABC.mdb";
CurrentDBInfo.DatabaseFilename = "ABC.mdb";
CurrentDBInfo.LastModifiedDataNTime = "12/22/2012 1:31:56 PM";
CurrentDBInfo.IsXmlFilesGenerated = true;

// add current db info into database details xml file
UIDbDetails.DatabaseInfo.Add(CurrentDBInfo);

// update database details xml file
    UIDbDetails.Save(dbDetailsXmlFileWithPath);


Output:
<?xml version="1.0"?>
<UIDatabaseDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <DatabaseInfo>   
    <UIDatabaseInfo>
      <DatabaseName>ABC.mdb</DatabaseName>
      <DatabaseFilename>ABC.mdb</DatabaseFilename>
      <LastModifiedDataNTime>12/22/2012 1:31:56 PM</LastModifiedDataNTime>
      <IsXmlFilesGenerated>true</IsXmlFilesGenerated>
    </UIDatabaseInfo>
  </DatabaseInfo>
</UIDatabaseDetails>
</UIDatabaseDetails>

No comments:

Post a Comment