"Unable to read beyond the end of the stream." exception using BinaryReader class and ReadString met

B

Bob Rock

I already found an alternative way to accomplish this (using
ReadBytes), still I'd like to understand why I'm getting and error
reading a text file using the following method. The exception is
returned on the ReadString call.

public string BinaryRead(string fileName)
{
FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite);

BinaryReader reader = new BinaryReader(stream);
reader.BaseStream.Seek(0, SeekOrigin.Begin);

StringBuilder builder = new StringBuilder();

while(reader.PeekChar() > -1)
{
try
{
// The call to ReadString rises an exception.
builder.Append(reader.ReadString());
}
catch(Exception ex)
{
// Handle exception
}
}

return builder.ToString();
}


Bob Rock
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi Bob,

I guess that the reader goes out of sync. Is the file written using the
BinaryWriter?
I'm asking because the BinaryReader expects strings that it reads with its
ReadString method to be written in special format. That's it expects to find
encoded length of the string prefixing the string characters. If you try to
read normal text files, they obviously don't satisfy its format
expectations. In this case it is most likely to get exception like that.

If this is the case use StreamReader instead.
 
J

Jon Skeet [C# MVP]

Bob Rock said:
I already found an alternative way to accomplish this (using
ReadBytes), still I'd like to understand why I'm getting and error
reading a text file using the following method. The exception is
returned on the ReadString call.

ReadString tries to read a length-prefixed string - were the strings
written by BinaryWriter?

If you're trying to just read a text file, I suggest you use
StreamReader instead and ReadLine or ReadToEnd.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top