C# 读写二进制文件

            BinaryWriter bw;
            BinaryReader br;
            try
            {
                bw = new BinaryWriter(new FileStream("mydata",
                FileMode.Create));
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\n Cannot create file.");
                return;
            }
            try
            {
                bw.Write(0.0);
                bw.Write(1.5);
                bw.Write(2.5);
                bw.Write(3.5);
                bw.Write(1.5);
                bw.Write(2.5);
                bw.Write(6.5);
                bw.Write(1.5);
                bw.Write(1.5);
                bw.Write(1.5);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\n Cannot write to file.");
                return;
            }

            bw.Close();
            //read
            try
            {
                br = new BinaryReader(new FileStream("mydata",
                FileMode.Open));
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\n Cannot open file.");
                return;
            }
            try
            {
                br.BaseStream.Seek(0, SeekOrigin.Begin);
                while (br.BaseStream.Position < br.BaseStream.Length)
                {

                    double i = br.ReadDouble();
                    Console.WriteLine("Double data: {0}", i);
                }
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\n Cannot read from file.");
                return;
            }
            br.Close();

BinaryWriter  BinaryReader 这2个就是读写用的工具

打开文件  写的话 就直接Write(xxx)

读就先把指针弄到文件起始位置 

while (br.BaseStream.Position < br.BaseStream.Length)这个判断读完没

然后就一个一个内容按你存的规则读出来

你可能感兴趣的:(C#)