Socket.BeginSendFile Method

Definition

Sends a file asynchronously to a connected Socket object.

Overloads

BeginSendFile(String, Byte[], Byte[], TransmitFileOptions, AsyncCallback, Object)

Sends a file and buffers of data asynchronously to a connected Socket object.

BeginSendFile(String, AsyncCallback, Object)

Sends the file fileName to a connected Socket object using the UseDefaultWorkerThread flag.

BeginSendFile(String, Byte[], Byte[], TransmitFileOptions, AsyncCallback, Object)

Sends a file and buffers of data asynchronously to a connected Socket object.

public:
 IAsyncResult ^ BeginSendFile(System::String ^ fileName, cli::array <System::Byte> ^ preBuffer, cli::array <System::Byte> ^ postBuffer, System::Net::Sockets::TransmitFileOptions flags, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult? BeginSendFile (string fileName, byte[] preBuffer, byte[] postBuffer, System.Net.Sockets.TransmitFileOptions flags, AsyncCallback callback, object state);
public IAsyncResult BeginSendFile (string fileName, byte[] preBuffer, byte[] postBuffer, System.Net.Sockets.TransmitFileOptions flags, AsyncCallback callback, object state);
member this.BeginSendFile : string * byte[] * byte[] * System.Net.Sockets.TransmitFileOptions * AsyncCallback * obj -> IAsyncResult
Public Function BeginSendFile (fileName As String, preBuffer As Byte(), postBuffer As Byte(), flags As TransmitFileOptions, callback As AsyncCallback, state As Object) As IAsyncResult

Parameters

fileName
String

A string that contains the path and name of the file to be sent. This parameter can be null.

preBuffer
Byte[]

A Byte array that contains data to be sent before the file is sent. This parameter can be null.

postBuffer
Byte[]

A Byte array that contains data to be sent after the file is sent. This parameter can be null.

flags
TransmitFileOptions

A bitwise combination of TransmitFileOptions values.

callback
AsyncCallback

An AsyncCallback delegate to be invoked when this operation completes. This parameter can be null.

state
Object

A user-defined object that contains state information for this request. This parameter can be null.

Returns

IAsyncResult

An IAsyncResult object that represents the asynchronous operation.

Exceptions

The Socket object has been closed.

An error occurred when attempting to access the socket. See remarks section below.

The operating system is not Windows NT or later.

-or-

The socket is not connected to a remote host.

The file fileName was not found.

Examples

The following code example creates and connects a socket for asynchronous communication and begins sending the file "text.txt" asynchronously to the remote host. In this example, a preBuffer and a postBuffer of data is created to send with the file and the default TransmitFileOptions value is used. The callback delegate calls EndSendFile to complete the transmission.

public:
   static void AsynchronousFileSendWithBuffers()
   {
      // Send a file asynchronously to the remote device. Send a buffer before the file and a buffer afterwards.
      // Establish the remote endpoint for the socket.
      IPHostEntry^ ipHostInfo = Dns::GetHostEntry( Dns::GetHostName() );
      IPAddress^ ipAddress = ipHostInfo->AddressList[ 0 ];
      IPEndPoint^ remoteEP = gcnew IPEndPoint( ipAddress,11000 );

      // Create a TCP/IP socket.
      Socket^ client = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );

      // Connect to the remote endpoint.
      client->BeginConnect( remoteEP, gcnew AsyncCallback( ConnectCallback ), client );

      // Wait for connect.
      connectDone->WaitOne();

      // Send a file fileName to the remote device with preBuffer and postBuffer data.
      // Create the preBuffer data.
      String^ string1 = String::Format( "This is text data that precedes the file.{0}", Environment::NewLine );
      array<Byte>^preBuf = Encoding::ASCII->GetBytes( string1 );

      // Create the postBuffer data.
      String^ string2 = String::Format( "This is text data that will follow the file.{0}", Environment::NewLine );
      array<Byte>^postBuf = Encoding::ASCII->GetBytes( string2 );

      // There is a file test.txt in the root directory.
      String^ fileName = "C:\\test.txt";

      //Send file fileName with buffers and default flags to the remote device.
      Console::WriteLine( fileName );
      client->BeginSendFile( fileName, preBuf, postBuf, static_cast<TransmitFileOptions>(0), gcnew AsyncCallback( AsynchronousFileSendCallback ), client );

      // Release the socket.
      client->Shutdown( SocketShutdown::Both );
      client->Close();
   }


private:
   static void AsynchronousFileSendCallback( IAsyncResult^ ar )
   {
      // Retrieve the socket from the state object.
      Socket^ client = dynamic_cast<Socket^>(ar->AsyncState);

      // Complete sending the data to the remote device.
      client->EndSendFile( ar );
      sendDone->Set();
   }
public static void AsynchronousFileSendWithBuffers()
{
    // Send a file asynchronously to the remote device. Send a buffer before the file and a buffer afterwards.

    // Establish the remote endpoint for the socket.
    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

    // Create a TCP/IP socket.
    Socket client = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp);

    // Connect to the remote endpoint.
    client.BeginConnect(remoteEP,
        new AsyncCallback(ConnectCallback), client);

    // Wait for connect.
    connectDone.WaitOne();

    // Send a file fileName to the remote device with preBuffer and postBuffer data.
    // Create the preBuffer data.
    string string1 = String.Format("This is text data that precedes the file.{0}", Environment.NewLine);
    byte[] preBuf = Encoding.ASCII.GetBytes(string1);

    // Create the postBuffer data.
    string string2 = String.Format("This is text data that will follow the file.{0}", Environment.NewLine);
    byte[] postBuf = Encoding.ASCII.GetBytes(string2);

    // There is a file test.txt in the root directory.
    string fileName = "C:\\test.txt";

    //Send file fileName with buffers and default flags to the remote device.
    Console.WriteLine(fileName);
    client.BeginSendFile(fileName, preBuf, postBuf, 0, new AsyncCallback(AsynchronousFileSendCallback), client);

    // Release the socket.
    client.Shutdown(SocketShutdown.Both);
    client.Close();
}

private static void AsynchronousFileSendCallback(IAsyncResult ar)
{
    // Retrieve the socket from the state object.
    Socket client = (Socket) ar.AsyncState;

    // Complete sending the data to the remote device.
    client.EndSendFile(ar);
    sendDone.Set();
}

Remarks

This overload requires the name of the file you want to send and a bitwise combination of TransmitFileOptions values. The preBuffer parameter contains any data you want to precede the file. postBuffer contains data you want to follow the file. If fileName is in the local directory, it may be identified with just the name of the file; otherwise, the full path and name of the file must be specified. Wildcards ("..\\myfile.txt") and UNC share names ("\\\\shared directory\\myfile.txt") are supported. If the file is not found, the exception FileNotFoundException is thrown.

The flags parameter provides the Window Sockets service provider with additional information about the file transfer. For more information about how to use this parameter, see TransmitFileOptions.

This method uses the TransmitFile function found in the Windows Sockets 2 API. For more information about the TransmitFile function and its flags, see the Windows Sockets documentation.

The BeginSendFile method starts an asynchronous send operation to the remote host established in the Connect, BeginConnect, Accept, or BeginAccept methods. BeginSendFile throws an exception if you do not first call Accept, BeginAccept, Connect, or BeginConnect. Calling the BeginSendFile method gives you the ability to send a file within a separate execution thread.

To complete the operation, you can create a callback method that is invoked by the AsyncCallback delegate parameter. To do this, at the very minimum, the state parameter must contain the Socket object being used for communication. If your callback needs more information, you can create a class or structure to hold the Socket and the other required information. Pass an instance of this custom object to the BeginSendFile method through the state parameter.

Your callback method must invoke the EndSendFile method. When your application calls BeginSendFile, the system uses a separate thread to execute the specified callback method, and blocks on EndSendFile until the Socket sends the entire file or throws an exception. For additional information on writing callback methods see Marshaling a Delegate as a Callback Method.

Although intended for connection-oriented protocols, BeginSendFile also works for connectionless protocols, provided that you first call the Connect or BeginConnect method to establish a default remote host. With connectionless protocols, you must also be sure that the size of your file does not exceed the maximum packet size of the underlying service provider. If it does, the datagram is not sent and BeginSendFile throws a SocketException exception.

Note

If you receive a SocketException exception, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in the .NET Framework.

Note

The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. After the first use of a particular context (a specific asynchronous Socket method, a specific Socket instance, and a specific callback), subsequent uses of that context will see a performance improvement.

Applies to

BeginSendFile(String, AsyncCallback, Object)

Sends the file fileName to a connected Socket object using the UseDefaultWorkerThread flag.

public:
 IAsyncResult ^ BeginSendFile(System::String ^ fileName, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginSendFile (string fileName, AsyncCallback? callback, object? state);
public IAsyncResult BeginSendFile (string fileName, AsyncCallback callback, object state);
member this.BeginSendFile : string * AsyncCallback * obj -> IAsyncResult
Public Function BeginSendFile (fileName As String, callback As AsyncCallback, state As Object) As IAsyncResult

Parameters

fileName
String

A string that contains the path and name of the file to send. This parameter can be null.

callback
AsyncCallback

The AsyncCallback delegate.

state
Object

An object that contains state information for this request.

Returns

IAsyncResult

An IAsyncResult object that represents the asynchronous send.

Exceptions

The Socket object has been closed.

The socket is not connected to a remote host.

The file fileName was not found.

An error occurred when attempting to access the socket. See remarks section below.

Examples

The following code example creates and connects a socket for asynchronous communication. First, the file "text.txt" is sent asynchronously to the remote host. The callback delegate calls EndSendFile to complete the transmission.

   static void AsynchronousFileSend()
   {
      // Send a file to a remote device.
      // Establish the remote endpoint for the socket.
      IPHostEntry^ ipHostInfo = Dns::GetHostEntry( Dns::GetHostName() );
      IPAddress^ ipAddress = ipHostInfo->AddressList[ 0 ];
      IPEndPoint^ remoteEP = gcnew IPEndPoint( ipAddress,11000 );

      // Create a TCP/IP socket.
      Socket^ client = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );

      // Connect to the remote endpoint.
      client->BeginConnect( remoteEP, gcnew AsyncCallback( ConnectCallback ), client );

      // Wait for connect.
      connectDone->WaitOne();

      // There is a text file test.txt in the root directory.
      String^ fileName = "C:\\test.txt";

      // Send file fileName to the remote device.
      Console::WriteLine( fileName );
      client->BeginSendFile( fileName, gcnew AsyncCallback( FileSendCallback ), client );

      // Release the socket.
      client->Shutdown( SocketShutdown::Both );
      client->Close();
   }

private:
   static void FileSendCallback( IAsyncResult^ ar )
   {
      // Retrieve the socket from the state object.
      Socket^ client = dynamic_cast<Socket^>(ar->AsyncState);

      // Complete sending the data to the remote device.
      client->EndSendFile( ar );
      sendDone->Set();
   }

public static void AsynchronousFileSend()
{
    // Send a file to a remote device.

    // Establish the remote endpoint for the socket.
    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

    // Create a TCP/IP socket.
    Socket client = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp);

    // Connect to the remote endpoint.
    client.BeginConnect(remoteEP,
        new AsyncCallback(ConnectCallback), client);

    // Wait for connect.
    connectDone.WaitOne();

    // There is a text file test.txt in the root directory.
    string fileName = "C:\\test.txt";

    // Send file fileName to the remote device.
    Console.WriteLine(fileName);
    client.BeginSendFile(fileName, new AsyncCallback(FileSendCallback), client);

    // Release the socket.
    client.Shutdown(SocketShutdown.Both);
    client.Close();
}

private static void FileSendCallback(IAsyncResult ar)
{
    // Retrieve the socket from the state object.
    Socket client = (Socket) ar.AsyncState;

    // Complete sending the data to the remote device.
    client.EndSendFile(ar);
    sendDone.Set();
}

Remarks

This overload sends the file fileName to the connected socket. If fileName is in the local directory, it may be identified with just the name of the file; otherwise, the full path and name of the file must be specified. Wildcards ("..\\myfile.txt") and UNC share names ("\\\\shared directory\\myfile.txt") are supported. If the file is not found, the exception FileNotFoundException is thrown.

This method uses the TransmitFile function found in the Windows Sockets 2 API. For more information about the TransmitFile function and its flags, see the Windows Sockets documentation.

The BeginSendFile method starts an asynchronous send operation to the remote host established in the Connect,BeginConnect, Accept, or BeginAccept methods. BeginSendFile throws an exception if you do not first call Accept, BeginAccept, Connect, or BeginConnect. Calling the BeginSendFile method enables you to send a file within a separate execution thread.

To complete the operation, you can create a callback method that is invoked by the AsyncCallback delegate parameter. To do this, at the very minimum, the state parameter must contain the Socket object being used for communication. If your callback needs more information, you can create a class or structure to hold the Socket and the other required information. Pass an instance of this custom object to the BeginSendFile method through the state parameter.

Your callback method must invoke the EndSendFile method. When your application calls BeginSendFile, the system uses a separate thread to execute the specified callback method, and blocks on EndSendFile until the Socket sends the entire file or throws an exception. For additional information on writing callback methods see Marshaling a Delegate as a Callback Method.

Although intended for connection-oriented protocols, BeginSendFile also works for connectionless protocols, provided that you first call the Connect or BeginConnect method to establish a default remote host. With connectionless protocols, you must be sure that the size of your file does not exceed the maximum packet size of the underlying service provider. If it does, the datagram is not sent and BeginSendFile throws a SocketException exception.

Note

If you receive a SocketException exception, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in the .NET Framework.

Note

The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. After the first use of a particular context (a specific asynchronous Socket method, a specific Socket instance, and a specific callback), subsequent uses of that context will see a performance improvement.

Applies to