返回顶部

收藏

通用序列化方法

更多

static void Main(string[] args) { Person p = new Person() { Name = "John Doe", Age = 42 }; XmlHelper.Serialize(p, @"D:\test.xml"); Person p2 = new Person(); p2 = XmlHelper.Deserialize(@"D:\test.xml"); Console.WriteLine("Name: " + p2.Name); Console.WriteLine("Age: " + p2.Age); Console.Read(); }

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

public static class XmlHelper
{
    /// <summary>
    /// Serializes the data in the object to the designated file path
    /// </summary>
    /// <typeparam name="T">Type of Object to serialize</typeparam>
    /// <param name="dataToSerialize">Object to serialize</param>
    /// <param name="filePath">FilePath for the XML file</param>
    public static void Serialize<T>(T dataToSerialize, string filePath)
    {
        try
        {
            using (Stream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
                writer.Formatting = Formatting.Indented;
                serializer.Serialize(writer, dataToSerialize);
                writer.Close();
            }
        }
        catch
        {
            throw;
        }
    }

    /// <summary>
    /// Deserializes the data in the XML file into an object
    /// </summary>
    /// <typeparam name="T">Type of object to deserialize</typeparam>
    /// <param name="filePath">FilePath to XML file</param>
    /// <returns>Object containing deserialized data</returns>
    public static T Deserialize<T>(string filePath)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T serializedData;

            using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                serializedData = (T)serializer.Deserialize(stream);
            }

            return serializedData;
        }
        catch
        {
            throw;
        }
    }
}

标签:c#

收藏

0人收藏

支持

0

反对

0

发表评论