1

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 ?

2 Answers 2

1

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());
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Well Still getting same exception
1

ReadString() method requires special format in the string, with prefixed of length on the start of each read.

Instead of having a special format you can just read it like so:

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

1 Comment

Same Expception occured

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.