NetworkStream.DataAvailable Property
Gets a value that indicates whether data is available on the NetworkStream to be read.
Assembly: System (in System.dll)
Property Value
Type: System.Booleantrue 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.");
}
Available since 1.1