Search code examples
c#binaryreader

BinaryReader C# - Check if there are bytes left


I was wondering if there is any method or property that allow us to see if there are available bytes to read in the stream associated to a BinaryReader (in my case, it is a NetworkStream, since I am performing a TCP communication). I have checked the documentation and the only method I have seen is PeekChar(), but it only checks if there is a next byte (character), so in case there are many bytes to read, making a while loop to increase a counter may be inneficient.

Regarding the TCP communication, the problem is that the application protocol behind the TCP was not defined by me, and I am just trying to figure out how it works! Of course there will be some "length field" that will give me some clues about the bytes to read, but right know I am just checking how it works and this question came to my mind.


Solution

  • The BinaryReader itself doesn't have a DataAvailable property, but the NetworkStream does.

    NetworkStream stream = new NetworkStream(socket);
    BinaryReader reader = new BinaryReader(stream);
    
    while (true)
    {
        if (stream.DataAvailable)
        {
            // call reader.ReadBytes(...) like you normally would!
        }
        // do other stuff here!
        Thread.Sleep(100);
    }
    

    If you don't have a handle to the original NetworkStream at the point where you would call reader.ReadBytes(), you can use the BaseStream property.

    while (true)
    {
        NetworkStream stream = reader.BaseStream as NetworkStream;
        if (stream.DataAvailable)
        {
            // call reader.ReadBytes(...) like you normally would!
        }
        // do other stuff here!
        Thread.Sleep(100);
    }