代码如下
private void DownLoad(string Url,string SaveName)
{
//判断文件是否存在,存在就删除
if (File.Exists(SaveName))
{
System.IO.File.Delete(SaveName);
}
float percent = 0;//进度百分比
try
{
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(Url);
Myrq.UserAgent = “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)”;
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
System.IO.Stream st = myrp.GetResponseStream();
System.IO.Stream so = new System.IO.FileStream(SaveName, System.IO.FileMode.Create);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
so.Write(by, 0, osize);
osize = st.Read(by, 0, (int)by.Length);
percent = (float)totalDownloadedByte / (float)totalBytes * 100;
Console.WriteLine(“当前下载百分百:” + percent.ToString() + “%”);
}
so.Close();
st.Close();
Console.WriteLine(“当下载完成”);
}
catch
{
Console.WriteLine(“当下载失败”);
}
}
}
声明:
本文采用
BY-NC-SA
协议进行授权,如无注明均为原创,转载请注明转自
一颗大萝北
本文地址: C# 下载文件并获取下载百分百
本文地址: C# 下载文件并获取下载百分百