這篇文章主要介紹了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 ///
///
///
pr
{
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();
新聞熱點
疑難解答