给定一个URL,下载该网页内容的最有效代码是什么? 我只考虑HTML,而不是相关的图像,JS和CSS。

===============>>#1 票数:62 已采纳

public static void DownloadFile(string remoteFilename, string localFilename)
{
    WebClient client = new WebClient();
    client.DownloadFile(remoteFilename, localFilename);
}

===============>>#2 票数:25

System.Net.WebClient

来自MSDN:

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

public class Test
{
    public static void Main (string[] args)
    {
        if (args == null || args.Length == 0)
        {
            throw new ApplicationException ("Specify the URI of the resource to retrieve.");
        }
        WebClient client = new WebClient ();

        // Add a user agent header in case the 
        // requested URI contains a query.

        client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

        Stream data = client.OpenRead (args[0]);
        StreamReader reader = new StreamReader (data);
        string s = reader.ReadToEnd ();
        Console.WriteLine (s);
        data.Close ();
        reader.Close ();
    }
}

===============>>#3 票数:23

使用System.Net中的WebClient类; 在.NET 2.0及更高版本上。

WebClient Client = new WebClient ();
Client.DownloadFile("http://mysite.com/myfile.txt", " C:\myfile.txt");

===============>>#4 票数:7

这是我的答案,一个获取URL并返回字符串的方法

public static string downloadWebPage(string theURL)
    {
        //### download a web page to a string
        WebClient client = new WebClient();

        client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

        Stream data = client.OpenRead(theURL);
        StreamReader reader = new StreamReader(data);
        string s = reader.ReadToEnd();
        return s;
    }

===============>>#5 票数:6

WebClient.DownloadString

public static void DownloadString (string address)
{
    WebClient client = new WebClient ();
    string reply = client.DownloadString (address);

    Console.WriteLine (reply);
}

===============>>#6 票数:0

我认为这是下载速度最快的(低延迟下载速度时间)解决方案。

// WebClient vs HttpClient vs HttpWebRequest vs RestSharp
// در نهایت به نظرم روش زیر سریعترین روشه
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
Request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Request.Proxy = null;
Request.Method = "GET";
using (WebResponse Response = Request.GetResponse())
{
    using (StreamReader Reader = new StreamReader(Response.GetResponseStream()))
    {
        return Reader.ReadToEnd();
    }
}

  ask by Krishna Kumar translate from so

未解决问题?本站智能推荐: