Export (0) Print
Expand All

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. 
            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.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft