C# URLを指定してhtmlを取得する

  • 作成日 2021.07.20
  • 更新日 2022.04.12
  • C#
C# URLを指定してhtmlを取得する

C#で、WebClientを使用して、URLを指定してhtmlを取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

WebClient使い方

WebClientを使用すると、URLを指定してhtmlを取得することが可能です。

WebClient client = new WebClient();

client.Encoding = System.Text.Encoding.UTF8;

client.DownloadString(URL);

以下は、当サイトのhtmlを取得するコードとなります。

using System;
using System.IO;
using System.Net;
using System.Text;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {

            WebClient client = new WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
            Console.WriteLine(client.DownloadString("https://mebee.info/"));
            
            Console.ReadKey();

        }
    }
}

実行結果