1. 程式人生 > >C#利用WebClient 兩種方式下載文件

C#利用WebClient 兩種方式下載文件

sys end adf ati stream pac pub 利用 static

WebClient client = new WebClient();

第一種

string URLAddress = @"http://files.cnblogs.com/x4646/tree.zip";

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

利用webclient讀取html內容

public static string GetWebClient(string url)

{ string strHTML = ""; WebClient myWebClient = new WebClient(); Stream myStream = myWebClient.OpenRead(url); StreamReader sr = new StreamReader(myStream, Encoding.Default);//註意編碼 strHTML = sr.ReadToEnd();
myStream.Close(); return strHTML; }

C#利用WebClient 兩種方式下載文件