C uses WebClient to download files in two ways

  • 2021-12-04 19:30:37
  • OfStack

Recently, WebClient downloaded files in two ways, which are reserved for future inquiry.

Type 1


string URLAddress = @"http://xiazai.ofstack.com";

string receivePath=@"C:\";

client.DownloadFile(URLAddress, receivePath + System.IO.Path.GetFileName(URLAddress));

OK.

Type 2


   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(); 


Related articles: