5

我有一个基于某些标准启动网页的 C# Windows 窗体应用程序。

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

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

任何帮助将不胜感激。

4

5 回答 5

5

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

 var httpClient = new HttpClient();
 File.WriteAllText("C:\\google.txt",    
                           httpClient.GetStringAsync("http://www.google.com")
                                     .Result);  
于 2012-10-29T09:20:20.027 回答
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);
于 2012-10-29T09:17:36.453 回答
3

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

var webClient = new WebClient();
webClient.DownloadFile("http://www.google.com",@"c:\google.txt");
于 2012-10-29T09:30:46.053 回答
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 );
于 2012-10-29T09:15:46.760 回答
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包含网页的完整文本

于 2012-10-29T09:16:04.650 回答