程序開發步驟:
(1)在VS2005項目中添加一個窗體。
(2)在窗體上添加兩個TextBox文本框,分別用於獲得URL信息與保存文件的路徑信息。
(3)在窗體上添加兩個Button按鈕,用來觸發相應的事件,同時添加一個多行TextBox文本框,用於顯示信息。
(4)程序代碼如下。
public void TryRequset (string StrUrl)
{
HttpWebResponse response;
WebRequest request;
try
{
request = WebRequest.Create(StrUrl);
request.Credentials = CredentialCache.DefaultCredentials;
response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
this.richTextBox1.Text = responseFromServer.ToString();
reader.Close ();
dataStream.Close ();
response.Close();
}
catch
{
MessageBox.Show("URL格式不正確或連接不到internet");
return;
}
}
通過調用TryRequset方法將URL傳遞進出,並獲得目標機器的Html信息,實現代碼如下: private void button1_Click(object sender, EventArgs e)
通過WebClIEnt類的DownloadFile方法將讀取出的Html信息保存到本地機器的指定目錄,實現代碼如下:
{
if (this.textBox1.Text.Trim().ToString() != "")
{
this.TryRequset(this.textBox1.Text.Trim().ToString());
}
else
{
MessageBox.Show("請寫入正確的URL");
}
} private void saveInfo(string strPath,string strDown)
{
WebClient wC = new WebClIEnt();
wC.DownloadFile(strDown, strPath);
}
通過調用saveInfo方法將文件路徑傳入,並且限定保存的格式,實現代碼如下:
private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "文本文件|*.txt";
if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
{
this.textBox2.Text = this.saveFileDialog1.FileName;
if (this.textBox1.Text.Trim().ToString() != "")
{
saveInfo(this.textBox2.Text.Trim().ToString(),
this.textBox1.Text.Trim().ToString());
MessageBox.Show("保存成功");
}
else
{
MessageBox.Show("請寫入目標頁的URL");
this.textBox2.Text = string.Empty;
}
}
}