欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#利用WebClient实现两种方式下载文件

程序员文章站 2023-09-07 11:44:10
最近整理了webclient 两种方式下载文件 ,留作以后查询。 第一种 string urladdress = @"http://xiazai.jb51....

最近整理了webclient 两种方式下载文件 ,留作以后查询。

第一种

string urladdress = @"http://xiazai.jb51.net";

string receivepath=@"c:\";

client.downloadfile(urladdress, receivepath + system.io.path.getfilename(urladdress));

 就ok了。

第二种

 stream str = client.openread(urladdress);
 streamreader reader = new streamreader(str);
 byte[] mbyte = new byte[1000000];
 int allmybyte = (int)mbyte.length;
 int startmbyte = 0;

 while (allmybyte > 0)
 {

 int m = str.read(mbyte, startmbyte, allmybyte);
 if (m == 0)
  break;

 startmbyte += m;
 allmybyte -= m;
 }

 reader.dispose();
 str.dispose();

 string path = receivepath + system.io.path.getfilename(urladdress);
 filestream fstr = new filestream(path, filemode.openorcreate, fileaccess.write);
 fstr.write(mbyte, 0, startmbyte);
 fstr.flush();
 fstr.close(); 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。