SaveLoadCtrl.cs
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public class SaveLoadCtrl
{
public static byte[] ObjectToBytes(object obj)
{
using (MemoryStream ms = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
return ms.GetBuffer();
}
}
public static object BytesToObject(byte[] Bytes)
{
using (MemoryStream ms = new MemoryStream(Bytes))
{
IFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(ms);
}
}
public static void SaveData<T>(T obj, string path)
{
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, obj);
fs.Close();
}
public static T LoadData<T>(string path)
{
if (File.Exists(path))
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
if (fs.Length != 0)
{
BinaryFormatter bf = new BinaryFormatter();
T res = (T)bf.Deserialize(fs);
fs.Close();
return res;
}
fs.Close();
return default(T);
}
return default(T);
}
}
读取
SaveLoadC trl.LoadData<List<GXRS>>(Directory.GetCurrentDirectory() + "\GxRS1.dat");
存入
SaveLoadCtrl.SaveData<List<GXRS>>(dtList1, Directory.GetCurrentDirectory() + "\GxRS1.dat");