NetworkStream.DataAvailable Property

 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Gets a value that indicates whether data is available on the NetworkStream to be read.

Namespace:   System.Net.Sockets
Assembly:  System (in System.dll)

public virtual bool DataAvailable { get; }

Property Value

Type: System.Boolean

true if data is available on the stream to be read; otherwise, false.

Exception Condition
ObjectDisposedException

The NetworkStream is closed.

IOException

The underlying Socket is closed.

SocketException

Use the SocketException.ErrorCode property to obtain the specific error code, and refer to the Windows Sockets version 2 API error code documentation in MSDN for a detailed description of the error.

Use the DataAvailable property to determine if data is ready to be read. If DataAvailable is true, a call to Read returns immediately. If the remote host shuts down or closes the connection, DataAvailable may throw a SocketException.

The following code example reads from the NetworkStream as long as data is available.

      // Examples for CanRead, Read, and DataAvailable.

      // Check to see if this NetworkStream is readable.
      if(myNetworkStream.CanRead){
          byte[] myReadBuffer = new byte[1024];
          StringBuilder myCompleteMessage = new StringBuilder();
          int numberOfBytesRead = 0;

          // Incoming message may be larger than the buffer size.
          do{
               numberOfBytesRead = myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);

myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));

          }
          while(myNetworkStream.DataAvailable);

          // Print out the received message to the console.
          Console.WriteLine("You received the following message : " +
                                       myCompleteMessage);
      }
      else{
           Console.WriteLine("Sorry.  You cannot read from this NetworkStream.");
      }

.NET Framework
Available since 1.1
Return to top
Show: