C#序列化與反序列化
阿新 • • 發佈:2018-02-28
color bsp private start sys bin create body null
一、序列化:
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(); } }
C#序列化與反序列化