文件的写入
将对象序列化后存入文件,cmd表示你需要存的文件名,这地方我把存放的位置已经写死了。
public static void ObjToFile(Object o,String cmd)
{
FileStream fs = null;
BinaryFormatter bf = null;
try
{
fs = new FileStream("C:\\" + cmd + "data.dat", FileMode.Create);
bf = new BinaryFormatter();
bf.Serialize(fs, o);
}
catch (Exception e)
{
Console.WriteLine(e);
// throw;
}
finally
{
if (fs!=null)
{
//关闭Io流
fs.Close();
}
}
}
文件的读取
在这个地方我把文件转成String [] 类型的,这个你们可以改成你们自己所需要的类型就可以。这个地方的cmd是你们读取文件的文件名与上面的cmd是对应的。
public static Object fileToObj(string cmd)
{
String[] s = null;
FileStream fs = null;
BinaryFormatter bf = null;
try
{
fs = new FileStream("C:\\" + cmd + "data.dat", FileMode.OpenOrCreate);
bf = new BinaryFormatter();
}
catch (Exception e)
{
Console.WriteLine(e);
// throw;
}
finally
{
if (fs != null)
{
s = (string[]) bf.Deserialize(fs);
fs.Close();
}
}
return s;
}
}
有不足的地方希望大佬门指正![手动狗头]