using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CsCsDownloadFileAsync { public partial class Form1 : Form { [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AllocConsole(); //WebClientフィールド System.Net.WebClient downloadClient = null; public Form1() { InitializeComponent(); AllocConsole(); } private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; button2.Enabled = true; //ダウンロードしたファイルの保存先 string fileName = @"C:\test\1.zip"; //ダウンロード基のURL Uri u = new Uri("http://localhost/Test.zip"); //WebClientの作成 if (downloadClient == null) { downloadClient = new System.Net.WebClient(); //イベントハンドラの作成 downloadClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler( downloadClient_DownloadProgressChanged); downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler( downloadClient_DownloadFileCompleted); } //非同期ダウンロードを開始する downloadClient.DownloadFileAsync(u, fileName); } private void button2_Click(object sender, EventArgs e) { //非同期ダウンロードをキャンセルする if (downloadClient != null) downloadClient.CancelAsync(); } private void downloadClient_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e) { Console.WriteLine("{0}% ({1}byte 中 {2}byte) ダウンロードが終了しました。", e.ProgressPercentage, e.TotalBytesToReceive, e.BytesReceived); } private void downloadClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { if (e.Cancelled) Console.WriteLine("キャンセルされました。"); else if (e.Error != null) Console.WriteLine("エラー:{0}", e.Error.Message); else Console.WriteLine("ダウンロードが完了しました。"); button1.Enabled = true; button2.Enabled = false; } } }