C#二进制文件读取序列化与反序列化

float[] lxgfloat = { 45f, 67f, 99.0f };
                         string s1 = "李磊";
                        BinaryWriter bw = new BinaryWriter(File.Open( @"G:\1.dat", FileMode.Create));
                         foreach ( float f in lxgfloat)
                        {
                                bw.Write(f);
                        }
                        bw.Write(s1);
                        bw.Close();
                        BinaryReader br = new BinaryReader(File.Open( @"G:\1.dat", FileMode.Open));
                         long x = br.BaseStream.Length;
                         while (br.BaseStream.Position < x - 7)
                        {
                                 float f = br.ReadSingle();
                        }

                         string s2 = br.ReadString();
                        br.Close();

//序列化与反序列化

using System;    
using System.IO;    
using System.Runtime.Serialization;    
using System.Runtime.Serialization.Formatters.Binary;    
public class SerialTest{    
         public void SerializeNow()
        {    
                ClassToSerialize c= new ClassToSerialize();
                FileStream fileStream = new FileStream( "G:\\51PT\\07-05-24-10-26-30-0C.dat", FileMode.Create);    
                BinaryFormatter b= new BinaryFormatter();    
                b.Serialize(fileStream,c);    
                fileStream.Close();    
        }    
                 public void DeSerializeNow()
                {    
                        ClassToSerialize c= new ClassToSerialize();
                        FileStream fileStream = new FileStream( "G:\\51PT\\07-05-24-10-26-30-0C.dat", FileMode.Open, FileAccess.Read, FileShare.Read);    
                        BinaryFormatter b= new BinaryFormatter();     //SoapFormatter    
                        c=(ClassToSerialize)b.Deserialize(fileStream);    
                        Console.WriteLine(c.name);    
                        fileStream.Close();    
                }    
        
}    
[Serializable]    
public class ClassToSerialize{     public int id=1;     public string name= "005";    }

你可能感兴趣的:(二进制,反序列化,C#,序列化,it)