0 votes

Hi, my case:
- I want to check if the connection to FTP server is good or not
- I need to know when transfer sucess to annouce
- Lost connection and the software nonresponding need to break out if connection lost

Please advice

by (930 points)

1 Answer

+1 vote

You'll get an exception on any error.

During transfer you can subscribe to Progress event to monitor file upload/download progress.

by (301k points)

I can't use by using
using ProgressEventArgs progressEventArgs = new ProgressEventArgs();

Here's how you can subscribe to Ftp.Progress event:

private void Ftp_Progress(object sender, ProgressEventArgs e)
{
    this.BeginInvoke((MethodInvoker) (() =>
    {
        _progressBar.Value= (int) e.Percentage;
    }));
 }

private void btnUpload_Click(
    object sender, 
    EventArgs e)
{
    Thread thread = new Thread(() =>
    {
        try
        {
            using (Ftp ftp = new Ftp())
            {
                ftp.Progress += Ftp_Progress;

                ftp.Connect("ftp.example.com");     
                ftp.Login("ftptest", "cypher");

                ftp.Upload("d:\\file.txt", "report.txt");

                // When there is no exception -
                // Upload succeeded here.

                ftp.Close();
            }
         }
         catch (Exception ex)
         {
             Log(ex.ToString());
         }
    });
    thread.Start();
}

Thread didn't work. I tried try catch and it work:

Private void Ftp_Progress(object sender, ProgressEventArgs e)
{
    this.BeginInvoke((MethodInvoker)(() =>
        {
            progressBarS1.Value = (int)e.Percentage;
            if (progressBarS1.Value == 100)
            {
                MessageBox.Show("Sucessful");
            }
        }));
    }

    private void button_Click(object sender, EventArgs e)
    {
        using (Ftp ftp = new Ftp())
        {
            try
            {
                ftp.Progress += Ftp_Progress;

                string add = txtaddS4.Text;
                string user = txtuserS4.Text;
                string pass = txtpassS4.Text;

                ftp.Connect(add);
                ftp.Login(user, pass);

                ftp.Upload(
                    @"testconnection.txt", 
                    @"testconnection.txt");

                ftp.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fail");
            }
        }
    }
...