c#序列化与反序列化(文本)

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class Serialize
{
    static public void DoSerialize<T>(T obj, string path)
    {
        using (FileStream fs = new FileStream(path, FileMode.Create))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, obj);
        }
    }
    static public T DoDeSerialize<T>(string path)
    {
        FileInfo fi = new FileInfo(path);
        T t;
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                t = (T)formatter.Deserialize(fs);
            }
            return t;
        }
        catch
        {
            return default(T);
        }
    }

    static public void SaveFile(string[] _content, string _path)
    {
        using (FileStream fs = new FileStream(_path, FileMode.Create, FileAccess.Write))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                for (int i = 0; i < _content.Length; i++)
                {
                    sw.WriteLine(_content[i]);
                }
            }
        }
    }
}

  

posted on 2017-03-31 15:17  yungs  阅读(489)  评论(0编辑  收藏  举报