Im getting error Unable to read beyond the end of the stream why?
You should use a more reliable way of figuring out when you are at the end of the stream, rather than rolling your own counter with sizeof(int)
. Your method may not be precise enough, and the fact that you are using an unsafe code for that is also not too good.
One way probe if you are at the end of the stream or not is to use the PeekChar
method:
while (br.PeekChar() != -1)
{
// 3.
// Read integer.
int v = br.ReadInt32();
textBox1.Text = v.ToString();
}
A more common solution is to write the number of int
s that you are saving in a binary file in front of the actual list of integers. This way you know when to stop without relying on the length or the position of the stream.
One reason your code could fail is if file contains extra bytes (i.e. 7 byte long file). Your code will trip on last 3 bytes.
To fix - consider computing number of integers in advance and using for
to read:
var count = br.BaseStream.Length / sizeof(int);
for (var i = 0; i < count; i++)
{
int v = br.ReadInt32();
textBox1.Text = v.ToString();
}
Note that this code will simply ignore last 1-3 bytes if they are there.