Search code examples
c#visual-studiostreambinaryreader

Can't Display proper result with Binary Reader


i have made two functions using binary streams

first one takes array as an arguement and writes data in file ... code:

      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);
                    }

                }

            }
        }

Second one should read the data:

  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

but when i run the code i get the following exception

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

what can be a problem ?


Solution

  • You should build the loop by considering BaseStream.Position

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