カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

HTMLソースを取得する VisualC#

System.Net.WebClientクラスを使用してHTMLソースを取得します。

//参照を追加
using System.Net;

・単純なダウンロード

//WebClientの作成
WebClient wc = new WebClient();

//文字コードを指定(Shift_JIS)
wc.Encoding = Encoding.GetEncoding(932);

//HTMLソースをダウンロードする
string source = wc.DownloadString(url);

//後始末
wc.Dispose();

・Timeout設定ができるようにするには

//文字コードを指定(Shift_JIS)
Encoding enc = Encoding.GetEncoding(932);

HttpWebRequest req =
    (HttpWebRequest)WebRequest.Create(url);

req.Timeout = 3000;

WebResponse res = req.GetResponse();

//文字コードを指定(Shift_JIS)し、HTMLソースをダウンロードする
Stream st = res.GetResponseStream();
StreamReader sr = new StreamReader(st, enc);

source = sr.ReadToEnd();

//後始末
sr.Close();
st.Close();

文字コードについてはこちらをご覧ください。
[テキストファイルの読み込みと書き込み]

1,107 views

ファイルのダウンロード

System.Net.WebClientクラスを使用してファイルをダウンロードします

//参照を追加
using System.Net;

・単純なダウンロード

public static void getFile(string uri, string filename)
{
    WebClient wc = new WebClient();
    wc.DownloadFile(uri, filename);
    wc.Dispose();
}

・バイト配列でダウンロード

public static byte[] getFile(string uri)
{
    byte[] data;

    //WebClientの作成
    WebClient wc = new WebClient();
    //ファイルをダウンロードする
    try
    {
        data = wc.DownloadData(uri);

        //後始末
        wc.Dispose();

        if (data.Length < 2500)
        {
            return null;
        }
    }
    catch
    {
        data = null;
    }

    return data;
}

・バイト配列から書き込み保存

public static void SaveFile(byte[] data, string filename)
{
    FileStream fsTo = new FileStream(filename, FileMode.Create, FileAccess.Write);

    fsTo.Write(data, 0, data.Length);

    fsTo.Close();
}
1,559 views