PDFファイルをWebからダウンロードしてみる
というのを試してみました。
このサンプルを動かすためには、VisualStudioのツールボックスに.NETコントロールの「WebClientコントロール」を追加しとかなきゃいけません。
前回のブログで書いたやつですね。
自分のメモ的に残しておきます。
これは、非同期ダウンロードのサンプルです。
<<メソッドメモ>> DownloadStartButton => WindowsFormに適当に配置されたボタン DownloadCancelButton => WindowsFormに適当に配置されたボタン PdfDownloadProgressChanged => WebClientコントロールのイベント「DownloadProgressChanged」に紐付けられています PdfDownloadFileCompleted => WEbClientコントロールのイベント 「DownloadFileCompleted」に紐付けられています
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace DownloadPDF { public partial class MainForm : Form { public MainForm() { InitializeComponent(); DownloadStartButton.Enabled = true; DownloadCancelButton.Enabled = false; } /// <summary> /// ダウンロードスタート(非同期) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DownloadStartButton_Click(object sender, EventArgs e) { DownloadStartButton.Enabled = false; DownloadCancelButton.Enabled = true; string fileName = @"C:\work\develop\C#\DownloadPDF\DownloadPDF\bin\Debug\hoge.pdf"; // 保存PDFファイル名 Uri downloadURL = new Uri("http://www.eidos.ic.i.u-tokyo.ac.jp/~tau/lecture/computational_physics/docs/python-doc-2.7ja1-pdf/tutorial.pdf"); // ダウンロードするPDFファイルのURL Console.WriteLine(downloadURL.AbsoluteUri); PdfDownloadwebClient.DownloadFileAsync(downloadURL,fileName); // 非同期ダウンロード開始 } /// <summary> /// ダウンロードキャンセル処理(非同期) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DownloadCancelButton_Click(object sender, EventArgs e) { if (PdfDownloadwebClient != null) { PdfDownloadwebClient.CancelAsync(); } } /// <summary> /// ダウンロード経過表示 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PdfDownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e) { // ここでプログレスバー的なモノを表示できる。 Console.WriteLine("{0}% ({1}byte 中 {2}byte) ダウンロードが終了しました。", e.ProgressPercentage, e.TotalBytesToReceive, e.BytesReceived); } /// <summary> /// ダウンロード完了通知処理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PdfDownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled) { MessageBox.Show("ダウンロードがキャンセルされました", "報告", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } else if(e.Error != null) { MessageBox.Show("ダウンロードに失敗しました", "報告", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } else { MessageBox.Show("ダウンロードを完了しました","報告",MessageBoxButtons.OK,MessageBoxIcon.Information,MessageBoxDefaultButton.Button1); } DownloadStartButton.Enabled = true; DownloadCancelButton.Enabled = false; } } }