日期:2014-05-17 浏览次数:21302 次
/// <summary> /// 序列化一个对象到文件中 /// </summary> /// <param name="obj">对象</param> /// <param name="filename">文件名</param> /// <returns>是否正确序列化</returns> public static bool SerializeToFile(object obj,string filename) { try { Debug("开始序列化到文件->"+filename); IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, obj); stream.Close(); Debug("序列化到文件完毕!"); return true; } catch (Exception ex) { Info(ex); return false; } } /// <summary> /// 从文件反序列化一个对象出来 /// </summary> /// <param name="filename">文件名称</param> /// <returns>反序列化的结果对象</returns> public static object DeserializeFromFile(string filename) { Debug("开始从文件->" + filename+"-反序列化"); IFormatter formatter = new BinaryFormatter(); Stream stream =null; object obj = null; try { stream= new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); obj= formatter.Deserialize(stream); stream.Close(); Debug("从文件反序列化成功!"); } catch (Exception ex) { if (stream != null) stream.Close(); Info(ex); throw ex; } return obj; }