首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# WebRequest、WebResponse 與 WebClient 實作(二):下載網頁內容並儲存

     編輯:關於C語言

程式開發步驟

  1. 在 VS2005 專案中新增一個表單。
  2. 在表單上放置兩個 TextBox,分別用於輸入 URL 與儲存檔案路徑。
  3. 新增兩個 Button 觸發事件,並加入一個多行 TextBox 顯示資訊。
  4. 撰寫核心程式碼如下。

發送 HTTP 請求並取得回應

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 格式不正確或無法連線至網際網路");
        return;
    }
}

按鈕點擊事件呼叫請求方法

private void button1_Click(object sender, EventArgs e)
{
    if (this.textBox1.Text.Trim().ToString() != "")
    {
        this.TryRequset(this.textBox1.Text.Trim().ToString());
    }
    else
    {
        MessageBox.Show("請輸入正確的 URL");
    }
}

使用 WebClient 下載並儲存檔案

private void saveInfo(string strPath, string strDown)
{
    WebClient wC = new WebClient();
    wC.DownloadFile(strDown, strPath);
}

儲存按鈕事件:選擇路徑並觸發下載

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;
        }
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved