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

时间:2012-10-29 09:13:25

标签: c# winforms copy notepad

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

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

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

任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

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);

答案 2 :(得分:3)

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

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

答案 3 :(得分:1)

您需要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 );

答案 4 :(得分:0)

您可以使用网络客户端执行此操作:

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 包含网页的完整文本