. Net File Download and upload, web page capture using WebClient
We know that webrequest (httpwebrequest, ftpwebrequest) and webresponse (httpwebresponse, ftpwebresponse) can be used to download and upload files and capture webpages, but WebClient is easier to use.
// Download the page with downloadfile <br/> // in this way, the http://www.cftea.com/home page is saved to the C disk. <Br/> using (system. net. webClient client = new system. net. webClient () <br/>{< br/> client. downloadfile ("http://www.cftea.com/", "C: \ foo.txt "); <br/>}</P> <p> // capture the webpage with downloaddata <br/> // <br/> using (system. net. webClient client = new system. net. webClient () <br/>{< br/> byte [] bytes = client. downloaddata ("http://www.cftea.com/"); <br/> string STR = system. text. encoding. getencoding ("gb2312 "). Getstring (bytes); <br/>}</P> <p> // use openread to capture a webpage <br/> // assign the crawled webpage to the variable Str, let's use it. You can also use the openread method to obtain data streams. <Br/> using (system. net. webClient client = new system. net. webClient () <br/>{< br/> using (system. io. stream stream = client. openread ("http://www.cftea.com/") <br/>{< br/> using (system. io. streamreader reader = new system. io. streamreader (stream, system. text. encoding. getencoding ("gb2312") <br/>{< br/> string STR = reader. readtoend (); <br/> reader. close (); <br/>}< br/> stream. close (); <br/>}< BR/>}</P> <p> // use uploadfile to upload a file <br/> // compared with downloaddata and openread, WebClient also has the uploaddata and openwrite methods, however, the most common method is to upload files, that is, use the uploadfile method. <Br/> // pay attention to the first parameter of uploadfile. You must add the uploaded file name, which cannot be ftp://www.cftea.com /. <Br/> using (system. net. webClient client = new system. net. webClient () <br/>{< br/> client. credentials = new system. net. networkcredential ("username", "password"); <br/> client. uploadfile ("ftp://www.cftea.com/foo.txt", "C: \ foo.txt"); <br/>}
Source: http://www.cftea.com/c/2010/04/N71KIVEHY9BRFER5.asp