无法使用二进制 Reader 显示正确的结果

Can't Display proper result with Binary Reader

我用二进制流做了两个函数

第一个以数组为参数,将数据写入文件...代码:

      public static void BinaryWrite(List<person> People)
        {
            string path = @"C:\Users\User\Desktop\filestream.txt";

            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    for(int i=0;i<People.Count;i++)
                    {
                        bw.Write(People[i].name);
                        bw.Write(People[i].surname);
                        bw.Write(People[i].age);
                    }

                }

            }
        }

第二个应该读取数据:

  public static void BinaryRead()
    {
        string path = @"C:\Users\User\Desktop\filestream.txt";

        using (FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read))
        {
            using (BinaryReader br = new BinaryReader(fs))
            {
                for (int i = 0; i < br.BaseStream.Length; i++)
                {
                    Console.WriteLine(br.ReadString());
                }

            }
        }
    }

enter code here

但是当我 运行 代码时,我得到以下异常

System.IO.EndOfStreamException: 'Unable to read beyond the end of the stream.'

什么是问题?

您应该考虑 BaseStream.Position

来构建循环
using (BinaryReader br = new BinaryReader(fs))
{
    while(br.BaseStream.Position < br.BaseStream.Length)
    {
         Console.WriteLine(br.ReadString());
    }
}

ReadString() 方法要求字符串中的特殊格式,在每次读取的开头加上长度前缀。

您可以这样阅读它,而不是使用特殊格式:

using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
       using (BinaryReader br = new BinaryReader(fs))
       {
            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                 Console.WriteLine((char)br.Read());
            }
        }
}