NetworkStream.CanRead Property


Gets a value that indicates whether the NetworkStream supports reading.

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

public override bool CanRead { get; }

Property Value

Type: System.Boolean

true if data can be read from the stream; otherwise, false. The default value is true.

If CanRead is true, NetworkStream allows calls to the Read method. Provide the appropriate FileAccess enumerated value in the constructor to set the readability and writability of the NetworkStream. The CanRead property is set when the NetworkStream is initialized.

The following code example checks CanRead to verify that the NetworkStream is readable. It then performs a read operation on the NetworkStream.

      // Examples for CanRead, Read, and DataAvailable.

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

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

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


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

.NET Framework
Available since 1.1
Return to top