最快的C#代码下载网页
时间:2020-03-05 18:42:52 来源:igfitidea点击:
给定一个URL,下载该网页内容的最有效的代码是什么?我只考虑HTML,而不考虑关联的图像,JS和CSS。
解决方案
回答
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 (); } }
回答
public static void DownloadFile(string remoteFilename, string localFilename) { WebClient client = new WebClient(); client.DownloadFile(remoteFilename, localFilename); }
回答
使用System.Net中的WebClient类;在.NET 2.0及更高版本上。
WebClient Client = new WebClient (); Client.DownloadFile("http://mysite.com/myfile.txt", " C:\myfile.txt");