一、序列化:
1 public void SerilizeData() 2 { 3 FileStream fs = null; 4 try 5 { 6 MainOperator mainOperator = new MainOperator();//创建MainOperator类的对象 7 fs = new FileStream(Application.StartupPath+@"\test.obj", FileMode.Create); 8 BinaryFormatter formatter = new BinaryFormatter(); 9 formatter.Serialize(fs, mainOperator); //对MainOperator 类进行序列化 10 } 11 catch (Exception ex) 12 { 13 MessageBox.Show(this.GetType().Name, new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name, ex.Message); 14 } 15 if (fs != null) 16 { 17 fs.Close();//释放 18 } 19 20 }
二、反序列化:
private void DeserilizeData() { FileStream fs = null; try { fs = new FileStream(Application.StartupPath + @"\test.obj", FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); mainOperator = (MainOperator)formatter.Deserialize(fs);//对MainOperator类反序列化 } catch (Exception ex) {} if (fs != null) { fs.Close(); } }