BinaryReader 和BinaryWriter 读写类对象

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace ConsoleApplication1
{
     
        public class INFO
        {
            public Int32 a { get; set; }
            public string b { get; set; }
            public string c { get; set; }

            public INFO()
            {
                a = 0;
                b = "";
                c = "";
            }

           

            public void ReadFromStream(Stream ms)
            {
              
                BinaryReader binReader = new BinaryReader(ms);
                this.a = binReader.ReadInt32();
                this.b = binReader.ReadString();
                this.c = binReader.ReadString();
            }

            public void WriteToStream(Stream ms)
            {
                BinaryWriter binWriter = new BinaryWriter(ms);
                binWriter.Write(this.a);
                binWriter.Write(this.b);
                binWriter.Write(this.c);


                Console.WriteLine(this.a.ToString());
                Console.WriteLine(this.b);
                Console.WriteLine(this.c);
                
                
            }

            static void Main(string[] args)
            {


                const string FilePath = @"D:\a.txt";
                FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                INFO g = new INFO();
                g.a = 12;
                g.b = "abcdefa";
                g.c = "小圆子";

                g.WriteToStream(fs);
             
                fs.Close();



                FileStream fsr = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                g.ReadFromStream(fsr);
                fsr.Close();
                Console.ReadLine();
            }
        }


    }

 

 

posted @ 2013-08-09 10:36  zzlp  阅读(398)  评论(0编辑  收藏  举报