This topic has not yet been rated - Rate this topic

NetworkStream.DataAvailable Property

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

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ