Skip to content

Instantly share code, notes, and snippets.

@nissuk
Created October 13, 2011 16:25
Show Gist options
  • Save nissuk/1284692 to your computer and use it in GitHub Desktop.
Save nissuk/1284692 to your computer and use it in GitHub Desktop.
C#: インターネット上のファイルをダウンロードして保存する単純な例(WebClient, WebRequest)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace Example
{
public static class WebRequestExtensions
{
/// <summary>
/// リソースをローカル ファイルにダウンロードします。
/// </summary>
/// <param name="request">リソースへのリクエスト。</param>
/// <param name="fileName">データを受信するローカル ファイルの名前。</param>
public static void DownloadFileTo(this WebRequest request, string fileName)
{
var response = request.GetResponse();
var stream = response.GetResponseStream();
using (var file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
{
int read;
byte[] buffer = new byte[1024];
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
file.Write(buffer, 0, read);
}
}
}
}
class Program
{
static void Main(string[] args)
{
var url = "http://www.google.co.jp/images/srpr/logo3w.png";
var baseDir = @"c:\Users\etc\test\";
// WebClientでファイルを保存します。
var client = new WebClient();
client.DownloadFile(url, baseDir + "1.png");
// WebRequest(+拡張メソッド)でファイルを保存します。
var request = WebRequest.Create(url);
request.DownloadFileTo(baseDir + "2.png");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment