我有一个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
任何帮助将不胜感激。
答案 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 包含网页的完整文本