private static BinaryFormatter Transfer = new BinaryFormatter();
public int BinaryFileSav()
{
//-----二进制文件写入并存储
saveFileDialog1.Filter = "数据文件(*.tifs)|*.tifs";
saveFileDialog1.Title = "文件存储";
saveFileDialog1.FileName = "新数据文件.tifs";
saveFileDialog1.ShowDialog();
Stream flstr = new FileStream(saveFileDialog1.FileName, FileMode.Create);
BinaryWriter sw = new BinaryWriter(flstr, Encoding.Unicode);
byte[] buffer = ChangeObjectToByte(obj);
sw.Write(buffer);
sw.Close();
flstr.Close();
return 0;
}
public int BinaryFileOpen()
{
//-----二进制文件读取
openFileDialog1.Filter = "数据文件(*.tifs)|*.tifs";
openFileDialog1.Title = "文件打开";
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
Stream flstr = new FileStream(openFileDialog1.FileName, FileMode.Open);
BinaryReader sr = new BinaryReader(flstr, Encoding.Unicode);
byte[] buffer = sr.ReadBytes((int)flstr.Length);
FrameForm.Tifs.fileinfo = (FileInfo)ChangeByteToObject(buffer);
sr.Close();
flstr.Close();
return 0;
}
#region ArrayList数组的二进制转化实现
/// <summary>
/// 序列化,存储用
/// </summary>
/// <param name="msg">要序列化的对象</param>
/// <returns>转化成的byte</returns>
private static byte[] ChangeObjectToByte(object obj)
{
try
{
MemoryStream ms = new MemoryStream();
//----将对象序列化
Transfer.Serialize(ms, obj);
byte[] buffer = ms.GetBuffer();
return buffer;
}
catch (Exception err)
{
return null;
}
}
/// <summary>
/// 反序列化,读取用
/// </summary>
/// <param name="buffer">二进制流</param>
private static object ChangeByteToObject(byte[] buffer)
{
try
{
MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length, true, true);
//----将流反序列化为对象
object obj = Transfer.Deserialize(ms);
return obj;
}
catch (Exception err)
{
return null;
}
}
#endregion
obj代表任意数据类型。另外,最好在该类前加注[Serializable] //----必须令相应的类实现可序列化标记接口
标签:存储,return,C#,二进制,buffer,new,flstr,序列化,byte From: https://blog.51cto.com/kenkao/5989790