代码改变世界

C#将数据本地持久化

2018-03-12 10:29 by 高效养猪倌, ... 阅读, ... 评论, 收藏, 编辑

有时候程序发生异常,用户正在编辑数据突然系统就蹦了,为了避免用户已经编辑的数据丢失,最好将用户正在操作的数据进行本地持久化

        /// <summary>
        /// 将对象序列化后保存到文件中
        /// </summary>
        public static void SerializeToFile<T>(T obj, string dataFile) {
            using(FileStream fileStream = File.Create(dataFile)) {
                BinaryFormatter binSerializer = new BinaryFormatter();
                binSerializer.Serialize(fileStream, obj);
            }
        }

        /// <summary>
        /// 从文件中读取数据并反序列化成对象
        /// </summary>
        public static T Deserialize<T>(string dataFile) {
            T obj = default(T);
            using(FileStream fileStream = File.OpenRead(dataFile)) {
                BinaryFormatter binDeserializer = new BinaryFormatter();
                obj = (T)binDeserializer.Deserialize(fileStream);
            }
            return obj;
        }
    Dictionary<string, object> transactionData = new Dictionary<string, object>() {
        { "Account","6226221601798333"},
        { "Name","张三"},
        { "TradeType","存款"},
        { "Amount",100.00d}
    };
    SerializeToFile(transactionData, "TD.txt");
    var currentData = Deserialize<Dictionary<string, object>>("TD.txt");
    foreach(var item in currentData) {
        Console.WriteLine("{0}-{1}",item.Key,item.Value);
    }