FtpWebRequest.EndGetRequestStream(IAsyncResult) Метод

Определение

Завершает асинхронную операцию в очереди, начинавшуюся с BeginGetRequestStream(AsyncCallback, Object).

public:
 override System::IO::Stream ^ EndGetRequestStream(IAsyncResult ^ asyncResult);
public override System.IO.Stream EndGetRequestStream (IAsyncResult asyncResult);
override this.EndGetRequestStream : IAsyncResult -> System.IO.Stream
Public Overrides Function EndGetRequestStream (asyncResult As IAsyncResult) As Stream

Параметры

asyncResult
IAsyncResult

Объект IAsyncResult, который был возвращен при начале операции.

Возвращаемое значение

Доступный для записи экземпляр Stream, который связан с этим экземпляром.

Исключения

asyncResult имеет значение null.

Параметр asyncResult не был получен путем вызова BeginGetRequestStream(AsyncCallback, Object).

Этот метод уже был вызван для операции, указанной в параметре asyncResult.

Примеры

В следующем примере кода показано завершение асинхронной операции для получения потока запроса. Этот пример кода является частью более крупного примера, предоставленного FtpWebRequest для обзора класса.

private:
   static void EndGetStreamCallback( IAsyncResult^ ar )
   {
      FtpState^ state = dynamic_cast<FtpState^>(ar->AsyncState);
      Stream^ requestStream = nullptr;

      // End the asynchronous call to get the request stream.
      try
      {
         requestStream = state->Request->EndGetRequestStream( ar );

         // Copy the file contents to the request stream.
         const int bufferLength = 2048;
         array<Byte>^buffer = gcnew array<Byte>(bufferLength);
         int count = 0;
         int readBytes = 0;
         FileStream^ stream = File::OpenRead( state->FileName );
         do
         {
            readBytes = stream->Read( buffer, 0, bufferLength );
            requestStream->Write( buffer, 0, bufferLength );
            count += readBytes;
         }
         while ( readBytes != 0 );
         Console::WriteLine( "Writing {0} bytes to the stream.", count );

         // IMPORTANT: Close the request stream before sending the request.
         requestStream->Close();

         // Asynchronously get the response to the upload request.
         state->Request->BeginGetResponse( gcnew AsyncCallback( EndGetResponseCallback ), state );
      }
      // Return exceptions to the main application thread.
      catch ( Exception^ e ) 
      {
         Console::WriteLine( "Could not get the request stream." );
         state->OperationException = e;
         state->OperationComplete->Set();
         return;
      }
   }
private static void EndGetStreamCallback(IAsyncResult ar)
{
    FtpState state = (FtpState) ar.AsyncState;

    Stream requestStream = null;
    // End the asynchronous call to get the request stream.
    try
    {
        requestStream = state.Request.EndGetRequestStream(ar);
        // Copy the file contents to the request stream.
        const int bufferLength = 2048;
        byte[] buffer = new byte[bufferLength];
        int count = 0;
        int readBytes = 0;
        FileStream stream = File.OpenRead(state.FileName);
        do
        {
            readBytes = stream.Read(buffer, 0, bufferLength);
            requestStream.Write(buffer, 0, readBytes);
            count += readBytes;
        }
        while (readBytes != 0);
        Console.WriteLine ("Writing {0} bytes to the stream.", count);
        // IMPORTANT: Close the request stream before sending the request.
        requestStream.Close();
        // Asynchronously get the response to the upload request.
        state.Request.BeginGetResponse(
            new AsyncCallback (EndGetResponseCallback),
            state
        );
    }
    // Return exceptions to the main application thread.
    catch (Exception e)
    {
        Console.WriteLine("Could not get the request stream.");
        state.OperationException = e;
        state.OperationComplete.Set();
        return;
    }
}

Комментарии

Если операция не завершена, EndGetRequestStream метод блокируется до завершения операции. Чтобы определить, завершена ли операция, проверка свойство перед вызовом IsCompletedEndGetRequestStream.

Помимо исключений, указанных в разделе "Исключения" EndGetRequestStream , повторно создает исключения, которые были созданы при открытии потока для записи.

Примечание

Данный член генерирует сведения трассировки, если в приложении включена трассировка сети. Дополнительные сведения см. в разделе Трассировка сети в платформа .NET Framework.

Применяется к

См. также раздел