增加命名空間:
using System.Net;
using System.IO;
/// <summary>
/// 下載檔案
/// </summary>
/// <param name="URL">要下載檔案網址</param>
public void downloadfile(string URL)
{
WebClient client=new WebClient();
int n = URL.LastIndexOf('/');
string URLAddress = URL.Substring(0,n); //取得網址
string fileName = URL.Substring(n+1,URL.Length-n-1); //取得檔案名稱
string Dir = Server.MapPath("./"); //下載檔案存放路徑
string Path = Dir+'\\'+fileName; //下載檔案存放完整路徑
Stream stream = client.OpenRead(URL);
StreamReader reader = new StreamReader(stream);
byte[] mbyte = new byte[100000];
int allbyte = (int)mbyte.Length;
int startbyte = 0;
while(allbyte>0) //迴圈讀取
{
int m = stream.Read(mbyte,startbyte,allbyte);
if(m==0)
break;
startbyte+=m;
allbyte-=m;
}
FileStream fstr = new FileStream(Path,FileMode.OpenOrCreate,FileAccess.Write);
fstr.Write(mbyte,0,startbyte); //寫檔案
stream.Close();
fstr.Close();
}
測試通過