数据契约序列化helper

public static class DataContractHelper
{

    public static void ToDCFile<T>(T obj, string path)   // 二进制序列化  
    {
        //路径
        FileStream fs = new FileStream(path, FileMode.Create);
        try
        {
            DataContractSerializer s = new DataContractSerializer(typeof(T));
            s.WriteObject(fs, obj);
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            fs.Close();
        }
    }

    public static T FromDCFile<T>(string path)   // 二进制反序列化  
    {
        FileStream fs = new FileStream(path, FileMode.Open);
        try
        {
            DataContractSerializer s = new DataContractSerializer(typeof(T));
            var obj = s.ReadObject(fs);
            return (T)obj;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return default(T);
        }
        finally
        {
            fs.Close();
        }

    }
}

猜你喜欢

转载自www.cnblogs.com/nocanstillbb/p/10557464.html