いくつかの基準に基づいて Web ページを起動する C# Windows フォーム アプリがあります。
ここで、アプリでそのページからすべてのテキスト (CSV 形式) を自動的にコピーし、メモ帳に貼り付けて保存したいと考えています。
コピーする必要があるデータの例へのリンクは次のとおりです 。アフリカ&フォーマット=1
どんな助けでも大歓迎です。
いくつかの基準に基づいて Web ページを起動する C# Windows フォーム アプリがあります。
ここで、アプリでそのページからすべてのテキスト (CSV 形式) を自動的にコピーし、メモ帳に貼り付けて保存したいと考えています。
コピーする必要があるデータの例へのリンクは次のとおりです 。アフリカ&フォーマット=1
どんな助けでも大歓迎です。
.NET 4.5の新しいおもちゃHttpClientを使用できます。例として、Google ページを取得する方法を示します。
var httpClient = new HttpClient();
File.WriteAllText("C:\\google.txt",
httpClient.GetStringAsync("http://www.google.com")
.Result);
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);
簡単な方法: 使用してファイル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 );
これを行うには、Web クライアントを使用できます。
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には Web ページの完全なテキストが含まれます