Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
NetworkStream Constructor (Socket, FileAccess, Boolean)

NetworkStream Constructor (Socket, FileAccess, Boolean)

Creates a new instance of the NetworkStream class for the specified Socket with the specified access rights and the specified Socket ownership.

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

public NetworkStream(
	Socket socket,
	FileAccess access,
	bool ownsSocket
)

Parameters

socket
Type: System.Net.Sockets.Socket

The Socket that the NetworkStream will use to send and receive data.

access
Type: System.IO.FileAccess

A bitwise combination of the FileAccess values that specifies the type of access given to the NetworkStream over the provided Socket.

ownsSocket
Type: System.Boolean

Set to true to indicate that the NetworkStream will take ownership of the Socket; otherwise, false.

ExceptionCondition
ArgumentNullException

The socket parameter is null.

IOException

The socket parameter is not connected.

-or-

The SocketType property of the socket parameter is not SocketType.Stream.

-or-

The socket parameter is in a nonblocking state.

The NetworkStream is created with read/write access to the specified Socket. If the value of the ownsSocket parameter is true, the NetworkStream takes ownership of the underlying Socket, and calling the Close method also closes the underlying Socket.

The access parameter sets the CanRead and CanWrite properties of the NetworkStream. If you specify Write, then the NetworkStream allows calls to the Write method. If you specify Read, then the NetworkStream allows calls to the Read method. If you specify ReadWrite, both method calls are allowed.

The following code example creates a NetworkStream with the ability to read and write to the Socket. Ownership of the Socket is given to this NetworkStream by specifying true for the ownsSocket parameter.

        // Example for creating a NetworkStreams

        mySocket.Connect(myIpEndPoint);

        // Create the NetworkStream for communicating with the remote host.
        NetworkStream myNetworkStream;

        if (networkStreamOwnsSocket){
             myNetworkStream = new NetworkStream(mySocket, FileAccess.ReadWrite, true);          
        }
        else{
             myNetworkStream = new NetworkStream(mySocket, FileAccess.ReadWrite);     
        }

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Show:
© 2015 Microsoft