public bool DownFile(string URL, string Filename, ProgressBar Prog, int intT)
{
bool blnOK = false;
try
{
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
Prog.Maximum = (int)totalBytes;
System.IO.Stream st = myrp.GetResponseStream();
System.IO.Stream so = new System.IO.FileStream(Filename, 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;
Application.DoEvents();
so.Write(by, 0, osize);
if (intT == 1) Prog.Value = (int)totalDownloadedByte;
osize = st.Read(by, 0, (int)by.Length);
//lblJD.Text = totalDownloadedByte.ToString() + " / " + totalBytes.ToString();
}
so.Close();
st.Close();
blnOK = true;
}
catch (Exception err)
{
MessageBox.Show("错误" + err.Message);
}
finally
{
}
return blnOK;
}复制代码
c#中的,测试可以使用的,调用方法
bool blnDownloaded = DownFile("文件网络地址", strPath + "Update.exe", progressBar1, 1);
if (blnDownloaded)
{
lblState.Text = "下载升级完成!正在启动升级程序!";
Application.DoEvents();
}复制代码