函數|下載
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text;
private void button3_Click(object sender, System.EventArgs e)
{
string DownloadUrl=textBox3.Text;
string LocalPath=textBox4.Text;
if(downfile(DownloadUrl,LocalPath))
{
MessageBox.Show("下載完成");
}
else
{
MessageBox.Show("下載過程中出現錯誤:");
}
}
public bool downfile(string url,string LocalPath)
{
try
{
Uri u = new Uri(url);
HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u);
mRequest.Method = "GET";
mRequest.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse wr = (HttpWebResponse)mRequest.GetResponse();
Stream sIn = wr.GetResponseStream();
FileStream fs = new FileStream(LocalPath, FileMode.Create, FileAccess.Write);
long length = wr.ContentLength;
long i = 0;
decimal j=0;
while (i < length)
{
byte[] buffer = new byte[1024];
i += sIn.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
if((i % 1024)==0)
{
j=Math.Round(Convert.ToDecimal((Convert.ToDouble(i)/Convert.ToDouble(length))*100),4);
statusBar1.Text="當前下載檔案大小:"+length.ToString()+"位元組 當前下載大小:"+i+"位元組 下載進度"+j.ToString()+"%";
}
else
{
statusBar1.Text="當前下載檔案大小:"+length.ToString()+"位元組 當前下載大小:"+i+"位元組";
}
}
sIn.Close();
wr.Close();
fs.Close();
return true;
}
catch { return false; }
}