如何从某个网页复制所有文本并将其保存到记事本C#

我有一个C#Windows窗体应用程序,它根据某些条件启动网页。

现在我希望我的应用程序自动复制该页面中的所有文本(CSV格式)并粘贴并保存在记事本中。

以下是需要复制的数据示例的链接: http : //www.wunderground.com/history/airport/FAJS/2012/10/28/DailyHistory.html? req_city = Johannesburg& req_state=& req_statename= South+非洲和格式= 1

任何帮助将不胜感激。

http://msdn.microsoft.com/en-us/library/fhd1f0sw.aspx与http://www.dotnetspider.com/resources/21720-Writing-string-content-file.aspx相结合

public static void DownloadString () { WebClient client = new WebClient(); string reply = client.DownloadString("http://www.wunderground.com/history/airport/FAJS/2012/10/28/DailyHistory.html?req_city=Johannesburg&req_state=&req_statename=South+Africa&format=1"); StringBuilder stringData = new StringBuilder(); stringData = reply; FileStream fs = new FileStream(@"C:\Temp\tmp.txt", FileMode.Create); byte[] buffer = new byte[stringData.Length]; for (int i = 0; i < stringData.Length; i++) { buffer[i] = (byte)stringData[i]; } fs.Write(buffer, 0, buffer.Length); fs.Close(); } 

编辑 Adil使用WriteAllText方法,这更好。 所以你会得到这样的东西:

 WebClient client = new WebClient(); string reply = client.DownloadString("http://www.wunderground.com/history/airport/FAJS/2012/10/28/DailyHistory.html?req_city=Johannesburg&req_state=&req_statename=South+Africa&format=1"); System.IO.File.WriteAllText (@"C:\Temp\tmp.txt", reply); 

您可以使用.NET 4.5中的新玩具HttpClient ,例如如何获取谷歌页面:

  var httpClient = new HttpClient(); File.WriteAllText("C:\\google.txt", httpClient.GetStringAsync("http://www.google.com") .Result); 

简单方法:使用WebClient.DownloadFile并另存为.txt文件:

 var webClient = new WebClient(); webClient.DownloadFile("http://www.google.com",@"c:\google.txt"); 

您需要WebRequest来读取流并将其保存到字符串到文本文件。 您可以使用File.WriteAllText将其写入文件。

 WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html"); request.Credentials = CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse (); Console.WriteLine (response.StatusDescription); Stream dataStream = response.GetResponseStream (); StreamReader reader = new StreamReader (dataStream); string responseFromServer = reader.ReadToEnd (); System.IO.File.WriteAllText (@"D:\path.txt", responseFromServer ); 

您可以使用webclient执行此操作:

 System.Net.WebClient wc = new System.Net.WebClient(); byte[] raw = wc.DownloadData("http://www.wunderground.com/history/airport/FAJS/2012/10/28/DailyHistory.html?req_city=Johannesburg&req_state=&req_statename=South+Africa&format=1"); string webData = System.Text.Encoding.UTF8.GetString(raw); 

然后字符串webData包含网页的完整文本