Microsoft KB Archive/318121

= BUG: BinaryReader.ReadChars Loses Data When It Reaches End-of-File =

Article ID: 318121

Article Last Modified on 10/22/2003

-

APPLIES TO


 * Microsoft .NET Framework Class Libraries 1.0

-



This article was previously published under Q318121



This article references the following .NET Framework Class Library namespace:
 * System.IO



SYMPTOMS
If the BinaryReader.ReadChars method reaches the end of the stream, BinaryReader.ReadChars should return all of the characters that it reads.

However, if BinaryReader.ReadChars requests more characters than are available, BinaryReader.ReadChars returns only half of the characters when it reaches the end of the stream.



RESOLUTION
If you do not know how many characters remain in the stream, use one of the following methods to work around this problem:
 * Use the StreamReader class instead of the BinaryReader class, and then use StreamReader.Read(char[],int,int) to read a certain number of characters from the stream.
 * Read the stream as a byte array.

The &quot;More Information&quot; section of this article includes a code sample that reads the characters as a byte array and then converts the characters to a string.



STATUS
This bug was corrected in Microsoft .NET Framework Class Libraries 1.1.



MORE INFORMATION
When you work with binary streams, you usually encode the string length in binary format so that you know how many characters to read.

To determine whether the stream is too short, compare the length of the returned string to the number of characters that you request. If the request returns a shorter number of characters than you request, the end of the stream is reached.

To reproduce this problem, use the following code in a Microsoft Visual C# .NET console application: using System; using System.IO;

namespace ReadCharsBugNamespace {   ///     /// Demonstrates the BinaryReader.ReadChars bug and shows one workaround. /// To use the sample, create a file named File.dat that contains the string /// &quot;1234567890&quot;, and then save File.dat in the same folder as the executable file. ///    public class ReadCharsBugClass {       static void Main(string[] args) {           try {               // Read more than the number of chars in the stream. // &quot;12345657890&quot; should appear, but instead // &quot;123456&quot; appears.

BinaryReader br = new BinaryReader(File.Open(&quot;file.dat&quot;, FileMode.Open)); Console.WriteLine(br.ReadChars(255)); br.Close;

// This works; read the string as a byte array.

br = new BinaryReader(File.Open(&quot;file.dat&quot;, FileMode.Open)); byte[] output = br.ReadBytes(255); String outputString = Encoding.UTF8.GetString(output); Console.Write(outputString); br.Close; }           catch (Exception e)            { Console.WriteLine(&quot;Error: &quot; + e.Message); }       }    } }

