Click to Rate and Give Feedback
TechNet
TechNet Library
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2010/.NET Framework 4

Other versions are also available for the following:
.NET Framework Class Library
FtpWebRequest..::.Abort Method

Terminates an asynchronous FTP operation.

Namespace:  System.Net
Assembly:  System (in System.dll)
Visual Basic
Public Overrides Sub Abort
C#
public override void Abort()
Visual C++
public:
virtual void Abort() override
F#
abstract Abort : unit -> unit 
override Abort : unit -> unit 

If there is no operation in progress, this method does nothing. If a file transfer is in progress, this method terminates the transfer.

NoteNote

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

The following code example demonstrates how the user can terminate an asynchronous upload of a file from the local directory to the server.

Visual Basic
Public Class ApplicationMain
    Public Shared Sub Main()
        Dim wait As New ManualResetEvent(False)
        Dim uploader As New AsynchronousFtpUpLoader(wait)
        uploader.AllowAbortUpload("out.txt", "ftp://sharriso1/ftptests.txt")
        wait.WaitOne()
        If uploader.AsyncException IsNot Nothing Then
            Console.WriteLine(uploader.AsyncException.ToString())
        End If
    End Sub
End Class
Public Class AsynchronousFtpUpLoader
    Private wait As ManualResetEvent
    Private request As FtpWebRequest
    Private fileContents() As Byte
    Private _asyncException As Exception = Nothing

    Public Sub New(ByVal wait As ManualResetEvent)
        Me.wait = wait
    End Sub

    Public ReadOnly Property AsyncException() As Exception
        Get
            Return _asyncException
        End Get
    End Property

    Private Sub EndGetStreamCallback(ByVal ar As IAsyncResult)
        Dim requestStream As Stream = Nothing
        ' End the asynchronous call to get the request stream.
        Try
            requestStream = request.EndGetRequestStream(ar)
            ' Return exceptions to the main application thread.
        Catch e As Exception
            Console.WriteLine("Could not get the request stream.")
            _asyncException = e
            wait.Set()
            Return
        End Try
        ' Write the file contents to the request stream.
        requestStream.Write(fileContents, 0, fileContents.Length)
        Console.WriteLine("Writing {0} bytes to the stream.", fileContents.Length)
        ' IMPORTANT: Close the request stream before sending the request.
        requestStream.Close()
    End Sub


    ' The EndGetResponseCallback method  
    ' completes a call to BeginGetResponse.
    Private Sub EndGetResponseCallback(ByVal ar As IAsyncResult)
        Dim response As FtpWebResponse = Nothing
        Try
            response = CType(request.EndGetResponse(ar), FtpWebResponse)
            ' Return exceptions to the main application thread.
        Catch e As Exception
            Console.WriteLine("Error getting response.")
            _asyncException = e
            wait.Set()
        End Try
        Console.WriteLine("Upload status: {0}", response.StatusDescription)
        ' Signal the application thread that this operation is complete.
        wait.Set()
    End Sub
    Friend Sub AbortRequest(ByVal request As FtpWebRequest)
        request.Abort()
        Console.WriteLine("Request aborted!")
        wait.Set()
    End Sub

    Public Sub AllowAbortUpload(ByVal fileName As String, ByVal serverUri As String)
        request = CType(WebRequest.Create(serverUri), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.UploadFile
        ' Get the file to be uploaded and convert it to bytes.
        Dim sourceStream As New StreamReader(fileName)
        fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd())
        sourceStream.Close()
        ' Set the content length to the number of bytes in the file.
        request.ContentLength = fileContents.Length
        ' Asynchronously get the stream for the file contents.
        Dim ar As IAsyncResult = request.BeginGetRequestStream(New AsyncCallback(AddressOf EndGetStreamCallback), Nothing)
        Do While Not ar.IsCompleted
            Console.WriteLine("Press 'a' to abort writing to the request stream. Press any other key to continue...")
            Dim input As String = Console.ReadLine()
            If input = "a" Then
                AbortRequest(request)
                Return
            End If
        Loop
        Console.WriteLine("Sending the request asynchronously...")
        Dim responseAR As IAsyncResult = request.BeginGetResponse(New AsyncCallback(AddressOf EndGetResponseCallback), Nothing)

        Do While Not responseAR.IsCompleted
            Console.WriteLine("Press 'a' to abort the upload. Press any other key to continue.")
            Dim input As String = Console.ReadLine()
            If input = "a" Then
                AbortRequest(request)
                Return
            End If
        Loop
    End Sub
C#
public class ApplicationMain
{
    public static void Main()
    {
          ManualResetEvent wait = new ManualResetEvent(false);
          AsynchronousFtpUpLoader uploader = new AsynchronousFtpUpLoader(wait);
          uploader.AllowAbortUpload("out.txt", "ftp://sharriso1/ftptests.txt");
          wait.WaitOne();
          if (uploader.AsyncException != null)
          {
                Console.WriteLine(uploader.AsyncException.ToString());
          }
    }
}
    public class AsynchronousFtpUpLoader
    {
        ManualResetEvent wait;
        FtpWebRequest request;
        byte [] fileContents;
        Exception asyncException = null;

        public AsynchronousFtpUpLoader(ManualResetEvent wait)
        {
            this.wait = wait;
        }

        public Exception AsyncException
        {
            get { return asyncException;}
        }

        private void EndGetStreamCallback(IAsyncResult ar)
        {
            Stream requestStream = null;
            // End the asynchronous call to get the request stream.
            try
            {
                requestStream = request.EndGetRequestStream(ar);
            } 
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine("Could not get the request stream.");
                asyncException = e;
                wait.Set();
                return;
            }
            // Write the file contents to the request stream.
            requestStream.Write(fileContents, 0, fileContents.Length);
            Console.WriteLine ("Writing {0} bytes to the stream.", fileContents.Length);
            // IMPORTANT: Close the request stream before sending the request.
            requestStream.Close();
        }


        // The EndGetResponseCallback method  
        // completes a call to BeginGetResponse.
        private void EndGetResponseCallback(IAsyncResult ar)
        {
            FtpWebResponse response = null;
            try 
            {
                response = (FtpWebResponse) request.EndGetResponse(ar);
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine ("Error getting response.");
                asyncException = e;
                wait.Set();
            }
            Console.WriteLine("Upload status: {0}",response.StatusDescription);
            // Signal the application thread that this operation is complete.
            wait.Set();
        }
        internal void AbortRequest(FtpWebRequest request)
        {
            request.Abort();
            Console.WriteLine("Request aborted!");
            wait.Set();
        }

       public void AllowAbortUpload(string fileName, string serverUri)
       {
            request = (FtpWebRequest)WebRequest.Create(serverUri);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            // Get the file to be uploaded and convert it to bytes.
            StreamReader sourceStream = new StreamReader(fileName);
            fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            // Set the content length to the number of bytes in the file.
            request.ContentLength = fileContents.Length;
            // Asynchronously get the stream for the file contents.
            IAsyncResult ar = request.BeginGetRequestStream(
                new AsyncCallback (EndGetStreamCallback), null);
             while (!ar.IsCompleted)
            {
                Console.WriteLine("Press 'a' to abort writing to the request stream. Press any other key to continue...");
                string input = Console.ReadLine();
                if (input == "a")
                {
                    AbortRequest(request);
                    return;
                }
            }
            Console.WriteLine("Sending the request asynchronously...");
            IAsyncResult responseAR = request.BeginGetResponse(
                new AsyncCallback (EndGetResponseCallback), null);

            while (!responseAR.IsCompleted)
            {
                Console.WriteLine("Press 'a' to abort the upload. Press any other key to continue.");
                string input = Console.ReadLine();
                if (input == "a")
                {
                    AbortRequest(request);
                    return;
                }
            }
        }
Visual C++
public:
   void AbortUpload( String^ fileName, String^ serverUri )
   {
      request = dynamic_cast<FtpWebRequest^>(WebRequest::Create( serverUri ));
      request->Method = WebRequestMethods::Ftp::UploadFile;

      // Get the file to be uploaded and convert it to bytes.
      StreamReader^ sourceStream = gcnew StreamReader( fileName );
      fileContents = Encoding::UTF8->GetBytes( sourceStream->ReadToEnd() );
      sourceStream->Close();

      // Set the content length to the number of bytes in the file.
      request->ContentLength = fileContents->Length;

      // Asynchronously get the stream for the file contents.
      IAsyncResult^ ar = request->BeginGetRequestStream( gcnew AsyncCallback( this, &AsynchronousFtpUpLoader::EndGetStreamCallback ), nullptr );
      Console::WriteLine( "Getting the request stream asynchronously..." );
      Console::WriteLine( "Press 'a' to abort the upload or any other key to continue" );
      String^ input = Console::ReadLine();
      if ( input->Equals( "a" ) )
      {
         request->Abort();
         Console::WriteLine( "Request aborted" );
         return;
      }
   }

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Do we have to wait for "BeginGetRequestStream()" before continue with "BeginGetResponse()"?      Nghia Nong   |   Edit   |   Show History

Do we have to wait for "BeginGetRequestStream()" before continue with "BeginGetResponse()"?

If yes, so, I can change method "AllowAbortUpload()" as follows:

public void AllowAbortUpload(string fileName, string serverUri)
{
request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.UploadFile;
// Get the file to be uploaded and convert it to bytes.
StreamReader sourceStream = new StreamReader(fileName);
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
// Set the content length to the number of bytes in the file.
request.ContentLength = fileContents.Length;
// Asynchronously get the stream for the file contents.
IAsyncResult ar = request.BeginGetRequestStream(
new AsyncCallback (EndGetStreamCallback), null);

Console.WriteLine("Sending the request asynchronously...");
IAsyncResult responseAR = request.BeginGetResponse(
new AsyncCallback (EndGetResponseCallback), null);

while ((!responseAR.IsCompleted) || (!ar.IsCompleted))
{
Console.WriteLine("Press 'a' to abort the upload. Press any other key to continue.");
string input = Console.ReadLine();
if (input == "a")
{
AbortRequest(request);
return;
}
}
}

Thanks.

Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker