メモメモ
WebClientクラスを使ってファイルをダウンロードする
System.Net空間にあるWebClientクラスのDownloadFileメソッドを使えば指定URLのファイルを簡単にダウンロードすることができます。
DownloadFileメソッドは引数が二つあり、一つ目が欲しいファイルのアドレス、二つ目が保存先のパスとなっています。
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;
using System.Net;
namespace imagedownload
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnDownload_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient(); //System.Net
string url = this.txtURL.Text;
string filename = System.IO.Path.GetFileName(url);
try
{
wc.DownloadFile(url, filename);
}
catch (WebException exc)
{
MessageBox.Show(exc.ToString());
}
}
}
}
例では”txtURL”というテキストボックスと”btnDownload”というボタンを用意して、ボタンを押すと”txtURL”に記述されたアドレスのファイルをダウンロードしてくるようにしています。
パス名についてはそのアドレスからGetFileNameで取得してきたものを使用しています。
(※この場合アドレスの末尾がGETパラメータなどのとき失敗するので注意)。
用途が少々違うかな。メモメモ