文件读写(二进制,序列化与反序列化)

近日,在整理项目代码,偏重于文件读写方面。很是折腾了一番,最后发现这么写代码是最简单的,贴出来分享一下

    public class FileOperation
    {
        public static void SaveFileInfo<T>(T info, string path)
        {
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(fs, info);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("写文件{0}失败:{1}", path, ex.Message));
            }
        }

        public static T ReadFileInfo<T>(string path)
        {
            T info = default(T);
            if (File.Exists(path))
            {
                try
                {
                    using (FileStream fs = new FileStream(path, FileMode.Open))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        info = (T)formatter.Deserialize(fs);
                    };
                }
                catch (Exception ex)
                {
                    File.Delete(path);
                    Console.WriteLine(string.Format("读文件{0}失败:{1}", path, ex.Message));
                }
            }
            return info;
        }
    }

 

 

posted @ 2012-11-16 12:24  xuejiao  阅读(1001)  评论(0编辑  收藏  举报