這篇文章主要介紹了C# WebClient類用法執行個體,本文講解使用WebClient下載檔案、OpenWriter開啟一個流使用指定的方法將資料寫入到uri以及上傳檔案樣本,需要的朋友可以參考下
進來的項目中要實現能夠在windows service中調用指定項目的連結頁面。由於訪問頁面時候使用的是ie瀏覽器或其他瀏覽器,所以想起用webclient類。
如果只想從特定的URI請求檔案,則使用WebClient,它是最簡單的.NET類,它只用一兩條命令執行基本操作,.NET FRAMEWORK目前支援以http:、https和file:標識符開頭的uri。
WebClient下載檔案
使用webclient下載檔案有兩種方法,具體使用哪一種方法取決於檔案內容的處理方式,如果只想把檔案儲存到磁碟上,使用downloadfile()方法,此方法有兩個參數,即請求的uri和請求檔案的的資料儲存位置。
更常見的是,應用程式需要處理從web網站檢索的資料,為此要用到OpenRead方法,此方法返回一個Stream對象,然後,可以Stream對象從資料流提取到記憶體中。
樣本:OpenRead(string uri);
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21OpenRead(string uri)
#region 讀取指定uri的html
///
/// 讀取指定uri的html
///
///
///
private void button4_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
string uri = "http://127.0.0.1/rss/sina.aspx";
Stream stream = wc.OpenRead(uri);
StreamReader sr = new StreamReader(stream);
string strLine = "";
while ((strLine = sr.ReadLine()) != null)
{
this.listBox1.Items.Add(strLine);
}
sr.Close();
}
#endregion
樣本:OpenWriter(string uri,string method);
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19OpenWriter(string uri,string method)
#region 開啟一個流使用指定的方法將資料寫入到uri
///
/// 開啟一個流使用指定的方法將資料寫入到uri
///
///
///
private void button1_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
string uri = "http://192.168.0.35/cims30/rss.txt";
Stream stream = wc.OpenWrite(uri, "PUT");
StreamWriter sw = new StreamWriter(stream);
sw.WriteLine("HelloWorldHelloWorldHelloWorldHelloWorld");
sw.Flush();
sw.Close();
MessageBox.Show("OK");
}
#endregion
openwriter方法返回一個可寫的資料流,便於使用者把資料發送給uri,可以指定使用者把資料發送給主機的方法,預設是post,上例假定0.35的伺服器上有一個可寫的目錄刺馬s,這段代碼是在該目錄下建立rss.txt檔案,其內容為“HelloWorldHelloWorldHelloWorldHelloWorld”
上傳檔案
WebClient類提供了UploadFile()和UploadData()方法,在需要投遞HTML表單或上傳整個檔案時候,就可以使用這兩個方法。Uploadfile()方法把檔案上傳到指定的位置,其中檔案名稱字已經給出,uploaddata()方法把位元組數組提供的位元據上傳到指定的uri;
樣本:上傳檔案
?
#region 把本地檔案上傳到指定uri
///
/// 把本地檔案上傳到指定uri
///
///
///
private void button2_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
string targetPath = "http://127.0.0.1/rss/Data Configuration.zip";
string sourcePath = "d:Data Configuration.zip";
this.label1.Text = string.Format("uploading {0} to {1}", targetPath, sourcePath);
byte[] bt = wc.UploadFile(targetPath, "PUT", sourcePath);
MessageBox.Show("OK");
}
#endregion
#region 把資料緩衝區上傳到指定資源
///
/// 把資料緩衝區上傳到指定資源
///
///
///
private void button3_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
string targetPath = "kaifeng.jpg";
string sourcePath = @"C:test.jpg";
FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, bt.Length);
wc.UploadData(targetPath, "PUT", bt);
}
#endregion
webclient功能有限,特別是不能使用身分識別驗證認證,這樣,上傳資料時候問題出現,現在許多網站都不會接受沒有身分識別驗證的上傳檔案。儘管可以給請求添加標題資訊並檢查相應中的標題資訊,但這僅限於一般意義的檢查,對於任何一個協議,webclient沒有具體支援,。這是由於webclient是非常一般的類,可以使用任意協議發送請求和接受相應,它不能處理特定於任何協議的任何特性。