+1 vote

How should I use the ftp.Abort instruction during a large file download if the user wishes to cease the operation? Once the thread with the download has been started, is there a way to use this method so that it kills the download and safely closes the ftp operation in its thread?

by (750 points)
edited by

1 Answer

0 votes

You simply need to use Ftp.Abort method.

This method is thread safe. You can use it from any thread.
Put it in the method that is invoked when user cancels the transfer:

C#:

private Ftp _ftp;

private void BtnDownload_Click(object sender, EventArgs e)
{
    Thread thread = new Thread(BackgroundThread);
    thread.Start();
}

private void BackgroundThread()
{
    try
    {
        _ftp = new Ftp();

        _ftp.Connect("ftp-loc");
        _ftp.Login("login", "password");

        _ftp.Download(path);

        _ftp.Close();
    }
    finally
    {
        _ftp.Dispose();    
        _ftp = null;
    }
}

private void BtnStop_Click(System.Object sender, System.EventArgs e)
{
    this._ftp?.Abort();
}

VB.NET:

Private _ftp As Ftp

Private Sub BtnDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim thread As Thread = New Thread(AddressOf BackgroundThread)
    thread.Start()
End Sub

Private Sub BackgroundThread()
    Try
        _ftp = New Ftp()
        _ftp.Connect("ftp-loc")
        _ftp.Login("login", "password")
        _ftp.Download(path)
        _ftp.Close()
    Finally
        _ftp.Dispose()
        _ftp = Nothing
    End Try
End Sub

Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Me._ftp?.Abort()
End Sub

Please note that this is just a sample code, error handling is missing.

by (301k points)
edited by
I am really sorry but C (or whatever this is) is not a syntax I work with or understand. All above the BtnStop_Click sub is accepted, so please can you indicate how to achieve this in VB? I have tried various solutions but so far none work ...
There are many online C# -> VB converters.
Well thanks. I thought I had bought this code with 1 yr technical support ...
OK - thank you very much again. However with exactly all of your code, the final sub -

   Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Stop.Click
       Me._ftp?.Abort()
   End Sub

gives -

Error    1    Expression is not a method.
Error    2    The '?' character cannot be used here.

What have I got wrong? It's been a long day, apologies if this is dumb but there it is. I use Visual Studio 2010, only with VB.
If ? operator is unavailable (it's VB.NET 9 I think) use:
If _ftp IsNot Nothing Then _ftp.Abort()
...