序列化对象到文件

 

最初是为了把Cookie 保存到本地,然后随时加载这个Cookie免登陆的

后来把它改了泛型,可以保存所有有 Serializable 的类对象

public static bool WriteObjToDisk<T>(string file, T obj) where T:class
{
//file = file.Replace(":", ":");
if (file == "") return false;
using (System.IO.Stream stream = System.IO.File.Create(file))
{
try
{
//Console.Out.Write("Writing cookies to disk... ");
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(stream, obj);
//Console.Out.WriteLine("Done.");
return true;
}
catch (Exception e)
{
// Console.Out.WriteLine("Problem writing cookies to disk: " + e.GetType());
}
}
return false;
}

public static T ReadObjFromDisk<T>(string file) where T : class
{
// file = file.Replace(":", ":");
try
{
using (System.IO.Stream stream = System.IO.File.Open(file, System.IO.FileMode.Open))
{
// Console.Out.Write("Reading cookies from disk... ");
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
// Console.Out.WriteLine("Done.");
return (T)formatter.Deserialize(stream);
}
}
catch (Exception e)
{

return null;
}
}

posted @ 2015-11-26 11:59  zslm___  阅读(257)  评论(0编辑  收藏  举报