Socket.BeginSendFile Socket.BeginSendFile Socket.BeginSendFile Socket.BeginSendFile Method

定义

将文件异步发送到连接的 Socket 对象。Sends a file asynchronously to a connected Socket object.

重载

BeginSendFile(String, AsyncCallback, Object) BeginSendFile(String, AsyncCallback, Object) BeginSendFile(String, AsyncCallback, Object) BeginSendFile(String, AsyncCallback, Object)

使用 Socket 标志,将文件 fileName 发送到连接的 UseDefaultWorkerThread 对象。Sends the file fileName to a connected Socket object using the UseDefaultWorkerThread flag.

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

将文件和数据缓冲区异步发送到连接的 Socket 对象。Sends a file and buffers of data asynchronously to a connected Socket object.

BeginSendFile(String, AsyncCallback, Object) BeginSendFile(String, AsyncCallback, Object) BeginSendFile(String, AsyncCallback, Object) BeginSendFile(String, AsyncCallback, Object)

使用 Socket 标志,将文件 fileName 发送到连接的 UseDefaultWorkerThread 对象。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);
member this.BeginSendFile : string * AsyncCallback * obj -> IAsyncResult
Public Function BeginSendFile (fileName As String, callback As AsyncCallback, state As Object) As IAsyncResult

参数

fileName
String String String String

一个字符串,它包含要发送的文件的路径和名称。A string that contains the path and name of the file to send. 此参数可以为 nullThis parameter can be null.

state
Object Object Object Object

一个对象,它包含此请求的状态信息。An object that contains state information for this request.

返回

一个 IAsyncResult 对象,它表示异步发送。An IAsyncResult object that represents the asynchronous send.

异常

套接字未连接到远程主机。The socket is not connected to a remote host.

未找到文件 fileNameThe file fileName was not found.

尝试访问套接字时出错。An error occurred when attempting to access the socket. 请参见下面的备注部分。See remarks section below.

示例

下面的代码示例创建并连接的套接字进行异步通信。The following code example creates and connects a socket for asynchronous communication. 首先,"text.txt"的文件是以异步方式发送,到远程主机。First, the file "text.txt" is sent asynchronously to the remote host. 回调委托调用EndSendFile完成传输。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();
}

注解

此重载将该文件发送fileName到连接的套接字。This overload sends the file fileName to the connected socket. 如果fileName是在本地目录中,它可能会标识只是该文件的名称; 否则,必须指定完整路径和文件的名称。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. 通配符 ("...\\myfile.txt") 和 UNC 共享名 ("\\\\shared directory\\myfile.txt") 支持。Wildcards ("..\\myfile.txt") and UNC share names ("\\\\shared directory\\myfile.txt") are supported. 如果未找到文件,该异常FileNotFoundException引发。If the file is not found, the exception FileNotFoundException is thrown.

此方法使用TransmitFileWindows Sockets 2 API 中找到函数。This method uses the TransmitFile function found in the Windows Sockets 2 API. 有关详细信息TransmitFile函数和它的标志,请参阅Windows 套接字文档。For more information about the TransmitFile function and its flags, see the Windows Sockets documentation.

BeginSendFile方法启动异步发送操作中建立的远程主机ConnectBeginConnectAccept,或BeginAccept方法。The BeginSendFile method starts an asynchronous send operation to the remote host established in the Connect,BeginConnect, Accept, or BeginAccept methods. BeginSendFile 如果不首先调用将引发异常AcceptBeginAcceptConnect,或BeginConnectBeginSendFile throws an exception if you do not first call Accept, BeginAccept, Connect, or BeginConnect. 调用BeginSendFile方法使您能够发送单独的执行线程中的文件。Calling the BeginSendFile method enables you to send a file within a separate execution thread.

若要完成该操作,可以创建由调用的回调方法AsyncCallback委托参数。To complete the operation, you can create a callback method that is invoked by the AsyncCallback delegate parameter. 为此,在最低限度下,state参数必须包含Socket对象用于进行通信。To do this, at the very minimum, the state parameter must contain the Socket object being used for communication. 如果回调需要详细信息,可以创建类或结构,用于保存Socket和其他所需的信息。If your callback needs more information, you can create a class or structure to hold the Socket and the other required information. 传递到此自定义对象的实例BeginSendFile方法通过state参数。Pass an instance of this custom object to the BeginSendFile method through the state parameter.

回调方法必须调用EndSendFile方法。Your callback method must invoke the EndSendFile method. 当应用程序调用BeginSendFile,系统使用一个单独的线程来执行指定的回调方法,并阻止上EndSendFile直到Socket发送整个文件或引发异常。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.

适用于面向连接的协议,尽管BeginSendFile无连接协议,也适用,前提是先调用ConnectBeginConnect方法以建立默认远程主机。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. 如果是这样,不发送数据报并BeginSendFile引发SocketException异常。If it does, the datagram is not sent and BeginSendFile throws a SocketException exception.

备注

如果你收到SocketException异常,请使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException exception, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步缓存的执行上下文 (的安全上下文中,被模拟的用户,并在调用上下文)Socket方法。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 后首次使用特定的上下文 (特定于异步Socket方法中,特定Socket实例和特定的回调),以后使用该上下文将看到性能的改进。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.

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

将文件和数据缓冲区异步发送到连接的 Socket 对象。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);
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

参数

fileName
String String String String

一个字符串,它包含要发送的文件的路径和名称。A string that contains the path and name of the file to be sent. 此参数可以为 nullThis parameter can be null.

preBuffer
Byte[]

一个 Byte 数组,它包含发送文件前要发送的数据。A Byte array that contains data to be sent before the file is sent. 此参数可以为 nullThis parameter can be null.

postBuffer
Byte[]

一个 Byte 数组,它包含发送文件后要发送的数据。A Byte array that contains data to be sent after the file is sent. 此参数可以为 nullThis parameter can be null.

callback
AsyncCallback AsyncCallback AsyncCallback AsyncCallback

一个 AsyncCallback 委托,将在此操作完成时调用它。An AsyncCallback delegate to be invoked when this operation completes. 此参数可以为 nullThis parameter can be null.

state
Object Object Object Object

一个用户定义的对象,它包含此请求的状态信息。A user-defined object that contains state information for this request. 此参数可以为 nullThis parameter can be null.

返回

一个 IAsyncResult 对象,它表示异步操作。An IAsyncResult object that represents the asynchronous operation.

异常

尝试访问套接字时出错。An error occurred when attempting to access the socket. 请参见下面的备注部分。See remarks section below.

操作系统不是 Windows NT 或更高版本。The operating system is not Windows NT or later.

- 或 --or- 套接字未连接到远程主机。The socket is not connected to a remote host.

未找到文件 fileNameThe file fileName was not found.

示例

下面的代码示例创建和连接进行异步通信套接字并开始将文件"text.txt"以异步方式发送到远程主机。The following code example creates and connects a socket for asynchronous communication and begins sending the file "text.txt" asynchronously to the remote host. 在此示例中,preBuffer和一个postBuffer的数据创建要与文件和默认值一起发送TransmitFileOptions使用值。In this example, a preBuffer and a postBuffer of data is created to send with the file and the default TransmitFileOptions value is used. 回调委托调用EndSendFile完成传输。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();
}

注解

此重载需要的名称以及你想要发送的文件的按位组合TransmitFileOptions值。This overload requires the name of the file you want to send and a bitwise combination of TransmitFileOptions values. preBuffer参数包含你想要前加上该文件的任何数据。The preBuffer parameter contains any data you want to precede the file. postBuffer 包含你想要遵照该文件的数据。postBuffer contains data you want to follow the file. 如果fileName是在本地目录中,它可能会标识只是该文件的名称; 否则,必须指定完整路径和文件的名称。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. 通配符 ("...\\myfile.txt") 和 UNC 共享名 ("\\\\shared directory\\myfile.txt") 支持。Wildcards ("..\\myfile.txt") and UNC share names ("\\\\shared directory\\myfile.txt") are supported. 如果未找到文件,该异常FileNotFoundException引发。If the file is not found, the exception FileNotFoundException is thrown.

flags参数提供了关于文件传输的其他信息的窗口套接字服务提供程序。The flags parameter provides the Window Sockets service provider with additional information about the file transfer. 有关如何使用此参数的详细信息,请参阅TransmitFileOptionsFor more information about how to use this parameter, see TransmitFileOptions.

此方法使用TransmitFileWindows Sockets 2 API 中找到函数。This method uses the TransmitFile function found in the Windows Sockets 2 API. 有关详细信息TransmitFile函数和它的标志,请参阅Windows 套接字文档。For more information about the TransmitFile function and its flags, see the Windows Sockets documentation.

BeginSendFile方法启动异步发送操作中建立的远程主机ConnectBeginConnectAccept,或BeginAccept方法。The BeginSendFile method starts an asynchronous send operation to the remote host established in the Connect, BeginConnect, Accept, or BeginAccept methods. BeginSendFile 如果不首先调用将引发异常AcceptBeginAcceptConnect,或BeginConnectBeginSendFile throws an exception if you do not first call Accept, BeginAccept, Connect, or BeginConnect. 调用BeginSendFile方法使你能够发送单独的执行线程中的文件。Calling the BeginSendFile method gives you the ability to send a file within a separate execution thread.

若要完成该操作,可以创建由调用的回调方法AsyncCallback委托参数。To complete the operation, you can create a callback method that is invoked by the AsyncCallback delegate parameter. 为此,在最低限度下,state参数必须包含Socket对象用于进行通信。To do this, at the very minimum, the state parameter must contain the Socket object being used for communication. 如果回调需要详细信息,可以创建类或结构,用于保存Socket和其他所需的信息。If your callback needs more information, you can create a class or structure to hold the Socket and the other required information. 传递到此自定义对象的实例BeginSendFile方法通过state参数。Pass an instance of this custom object to the BeginSendFile method through the state parameter.

回调方法必须调用EndSendFile方法。Your callback method must invoke the EndSendFile method. 当应用程序调用BeginSendFile,系统使用一个单独的线程来执行指定的回调方法,并阻止上EndSendFile直到Socket发送整个文件或引发异常。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.

适用于面向连接的协议,尽管BeginSendFile无连接协议,也适用,前提是先调用ConnectBeginConnect方法以建立默认远程主机。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. 如果是这样,不发送数据报并BeginSendFile引发SocketException异常。If it does, the datagram is not sent and BeginSendFile throws a SocketException exception.

备注

如果你收到SocketException异常,请使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException exception, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步缓存的执行上下文 (的安全上下文中,被模拟的用户,并在调用上下文)Socket方法。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 后首次使用特定的上下文 (特定于异步Socket方法中,特定Socket实例和特定的回调),以后使用该上下文将看到性能的改进。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.

适用于