【C#】ネット上から画像のダウンロード
HttpClientクラスのGetAsyncメソッドを使います。
はてなフォトライフの下記URLの画像を取ってきます。
http://f.st-hatena.com/images/fotolife/s/shirakamisauto/20160120/20160120232256.png
using System; using System.Net.Http; using System.IO; namespace Downloader { class Program { static void Main(string[] args) { var uri = "http://f.st-hatena.com/images/fotolife/s/shirakamisauto/20160120/20160120232256.png"; DownloadImgAsync(uri, @"C:\Users\xxxxx\Desktop\IMG2.png"); //フォームに画像を表示 詳細は省く ImgDisplayByForm(@"C:\Users\xxxxx\Desktop\IMG2.png"); Console.ReadLine(); } static async void DownloadImgAsync(string imgUri, string outputPath) { var client = new HttpClient(); HttpResponseMessage res = await client.GetAsync( imgUri, HttpCompletionOption.ResponseContentRead); using (var fileStream = File.Create(outputPath)) using (var httpStream = await res.Content.ReadAsStreamAsync()) httpStream.CopyTo(fileStream); } } }
画像ダウンロードと銘打ってますが、ファイルならなんでも取ってこれます。
HttpResponseMessageのステータスコードが200以外だと失敗している可能性が高いです。
非同期実行なので、はてなフォトライフの全画像ダウンロードみたいなことをするとサーバー負荷かかると思うので注意。