以下为将一个对象序列化成二进制数据,以保存到数据库的方法:
对象的序列化
ProcessDataSource pd = new ProcessDataSource(txtTitle.Text, yAxisName, selectpointfield);
//初始化一个对象
System.IO.MemoryStream ms = new System.IO.MemoryStream();
MemoryStream 类创建这样的流,该流以内存而不是磁盘或网络连接作为支持存储区。MemoryStream 封装以无符号字节数组形式存储的数据,该数组在创建 MemoryStream 对象时被初始化,或者该数组可创建为空数组。可在内存中直接访问这些封装的数据。内存流可降低应用程序中对临时缓冲区和临时文件的需要。
byte[] temp = null;
BinaryFormatter formatter = new BinaryFormatter();
//(
BinaryFormatter
类的作用)以二进制格式将对象或整个连接对象图形序列化和反序列化。
formatter.Serialize(ms, pd); //将对象或具有指定顶级(根)的对象图形序列化为给定流
temp = ms.ToArray();
//提取内存流中的数据
int rowAffected = 0;
Graphs_Template_Entity graphTemplate = new Graphs_Template_Entity();
//保存对象
graphTemplate.GraphGUID = this.guid;
graphTemplate.GraphName = this.txtTitle.Text;
graphTemplate.TemplateType = GraphType.过程线.ToString();
raphTemplate.sItemGuid = this.sitemguid;
graphTemplate.Template =
temp; //
将生成的二进制数组赋值给对象属性。
graphTemplate.CreateUser = AppCore.Runtime.AppContext.UserName;
graphTemplate.CreateDate = DateTime.Now;
graphTemplate.sRemark = "";