FTPでファイルのダウンロードと進行状況の表示

C#Windows上のフォームから、FTPでファイルをダウンロードする必要があったので、以下で実装しました。

 

前提条件として、

  • ダウンロード中の進行状況の表示
  • ユーザによる途中キャンセル

が、ありました。

 

以下、フォームに

が、貼ってあるものとします。

 

キャンセルボタンのEnable化などは省略

 

>|cs|

        //ダウンロード中のフラグ
  private bool onDownloading = false;
  //ダウンロード用のWebClient
        private WebClient wc = null;

        //ダウンロードボタンクリック
        private void downloadButton_Click(object sender, EventArgs e)
        {
            Uri uri = new Uri("ダウンロード先のパス ftp://example.com/example.txt");
            if (wc == null)
            {
                wc = new WebClient();               

               //webClientに進行状況、完了時のイベントハンドラを追加
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
                wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
            }

   //ダウンロード開始
             wc.DownloadFileAsync(uri, "保存先のローカルパス")
             onDownloading = true;
        }

        //ダウンロードの進歩イベント
        private void wc_DownloadProgressChanged(Object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        //完了時のイベント
        private void wc_DownloadFileCompleted(Object sender, AsyncCompletedEventArgs e)
        {
            if ( (e.Error != null) && (!e.Cancelled) )
            {
                MessageBox.Show("ダウンロード中にエラーが発生しました。内容:" + e.Error.Message, "エラー",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("ダウンロードがキャンセルされました。", "完了", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("データのダウンロードが完了しました。", "完了", MessageBoxButtons.OK, MessageBoxIcon.Information); 
            }
            onDownloading = false;
        }

 

        //キャンセルボタンクリック
        private void cancelButton_Click(object sender, EventArgs e)
        {
            //ダウンロード中なら、ダウンロードをキャンセルする
            if (onDownloading)
            {
                if (wc != null)
                {
                    wc.CancelAsync();
                }
            }
        }