1. 从文件中获取二进制信息并反序列化,返回指定的type的对象
/// <summary>
/// 二进制反序列化,并返回指定的type的对象
/// </summary>
/// <param name="type">要返回类型的对象</param>
/// <param name="strPath">二进制文件完整路径</param>
/// <returns></returns>
private static object FromFile(Type type, string strPath)
{
if (type == (Type) null)
return (object) null;
object obj = (object) null;
if (!string.IsNullOrEmpty(strPath) && File.Exists(strPath))
{
System.IO.FileStream fileStream = new System.IO.FileStream(strPath, FileMode.Open, FileAccess.Read, FileShare.Read);
try
{
obj = new BinaryFormatter().Deserialize((Stream) fileStream);
fileStream.Close();
}
catch (Exception ex)
{
FormReportException.Report(ex);
fileStream.Close();
return obj;
}
}
return obj;
}
2. 将对象序列化为二进制,并存储到文件中
/// <summary>
/// 将对象序列化为二进制
/// </summary>
/// <param name="obj">需要序列化的对象</param>
/// <param name="strPath">二进制存储文件路径</param>
private static void ToFile(object obj, string strPath)
{
if (obj == null || string.IsNullOrEmpty(strPath))
return;
System.IO.FileStream fileStream = !File.Exists(strPath) ? new System.IO.FileStream(strPath, FileMode.OpenOrCreate) : new System.IO.FileStream(strPath, FileMode.Truncate);
try
{
new BinaryFormatter().Serialize((Stream) fileStream, obj);
fileStream.Close();
}
catch (Exception ex)
{
FormReportException.Report(ex);
fileStream.Close();
}
}
3. 使用
private DataTable m_dt;
public AntGISEditorSetting(IEngineEditor pEngineEditor)
{
string m_strFilePath = System.IO.Path.Combine(AntGIS.Desktop.Config.Path.Config, "Editor\\Option.dat");
if (!File.Exists(m_strFilePath))
{
this.m_dt = new DataTable();
this.m_dt.TableName = "EditorSetting";
this.m_dt.Columns.Add("SettingName", typeof (string));
this.m_dt.Columns.Add("SettingValue", typeof (object));
this.m_dt.Columns.Add("SettingType", typeof (string));
DataRow row1 = this.m_dt.NewRow();
row1[0] = (object) "OptionByArcGIS";
row1[1] = (object) false;
row1[2] = (object) "bool";
this.m_dt.Rows.Add(row1);
DataRow row2 = this.m_dt.NewRow();
row2[0] = (object) "AutoChamfer";
row2[1] = (object) false;
row2[2] = (object) "bool";
this.m_dt.Rows.Add(row2);
DataRow row3 = this.m_dt.NewRow();
row3[0] = (object) "AutoReShape";
row3[1] = (object) false;
row3[2] = (object) "bool";
this.m_dt.Rows.Add(row3);
//序列化二进制
ToFile(this.m_dt, this.m_strFilePath);
}
else
//反序列化二进制
this.m_dt = FromFile(typeof (DataTable), this.m_strFilePath) as DataTable;
}
网友评论