0

I receive following error:

“unable to read beyond the end of stream”

I write the file like this:

FileStream path = new FileStream(@"C:\Users\Moosa Raza\Desktop\byte.txt", FileMode.CreateNew); 
BinaryWriter file = new BinaryWriter(path); 
int a = int.Parse(Console.ReadLine()); 
double b = double.Parse(Console.ReadLine()); 
string c = Console.ReadLine(); 

file.Write(b); 
file.Write(c); 
file.Write(a);

input is a = 12, b = 13 and c = raza

Then read it like this:

FileStream path = new FileStream(@"C:\Users\Computer\Desktop\byte.txt", FileMode.Open);
BinaryReader s = new BinaryReader(path);
int a = s.ReadInt32();
double b = s.ReadDouble();
string c = s.ReadString();
Console.WriteLine("int = {0} , double = {1} , string = {2}",a,b,c);
Console.ReadKey();
Riven Callahan
  • 107
  • 1
  • 8
  • Possible duplicate of [Im getting error Unable to read beyond the end of the stream why?](https://stackoverflow.com/questions/11979889/im-getting-error-unable-to-read-beyond-the-end-of-the-stream-why) – Adrian Sep 25 '18 at 11:48
  • Hi. Have you verified that the file contains enough bytes to actually contain an Int32, a Double, and a String? – Lasse V. Karlsen Sep 25 '18 at 11:52
  • It means that you didn't write the same info to the file you're reading back. – CodeCaster Sep 25 '18 at 11:53
  • 1
    Could you provide us the byte.txt contents and the exact line of code where the exception gets throwed? – user11909 Sep 25 '18 at 12:00

2 Answers2

1

You must read the file in the exact same order you write it. According to your comment, the order in which you write is: double, string, int.

The reading code however, reads in the order int, double, string.

This causes the reader to read the wrong bytes, and interpret a certain value as an incorrect string length, thereby trying to read beyond the end of the file.

Make sure you read in the same order as you write.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0

please try this. By using 'using' scope, it will close the file when you finish writing or reading it. Also the code will be a bit cleaner.

        using (var sw = new StreamWriter(@"C:\Users\Computer\Desktop\byte.txt"))
        {
            sw.WriteLine(int.Parse(Console.ReadLine()));
            sw.WriteLine(double.Parse(Console.ReadLine()));
            sw.WriteLine(Console.ReadLine());
        }

        using (var sr = new StreamReader(@"C:\Users\Computer\Desktop\byte.txt"))
        {
           int a =  int.Parse(sr.ReadLine());
           double b =  double.Parse(sr.ReadLine());
           string c =  sr.ReadLine();
        } 
Joseph Wu
  • 4,786
  • 1
  • 21
  • 19