private void button1_Click(object sender, EventArgs e)
{
string URL = txtSourceDir.Text;
string filename = txtDestDir.Text;
if (DownloadFile(@"http://10.10.1.137/bjh/门禁管理系统/K6-SETUP/CDROM/Disk1/setup.exe", @"C:\setup.exe", progressBar1, label3))
{
MessageBox.Show("下载成功!");
this.Close();
}
else
MessageBox.Show("下载失败!");
}
public bool DownloadFile(string URL, string filename, ProgressBar prog, Label label1)
{
float percent = 0;
try
{
HttpWebRequest Myrq = (HttpWebRequest)WebRequest.Create(URL);
Myrq.Timeout = 5000;
HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();
myrp.Close();
long totalBytes = myrp.ContentLength;
if (prog != null)
{
prog.Maximum = (int)totalBytes;
}
Stream st = myrp.GetResponseStream();
Stream so = new FileStream(filename, 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 (prog != null)
{
prog.Value = (int)totalDownloadedByte;
}
osize = st.Read(by, 0, (int)by.Length);
percent = (float)totalDownloadedByte / (float)totalBytes * 100;
label3.Text = "当前补丁下载进度" + percent.ToString() + "%";
Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
}
so.Close();
st.Close();
myrp.Close();
}
catch (System.Exception)
{
return false;
}
return true;
}
到 HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse(); 这一句的时候 会报错 说是超时 哪位高手能教教我怎么改 在线等
可能是你的IIS部署问题.
你可以尝试在IE中直接输入http://10.10.1.137/bjh/门禁管理系统/K6-SETUP/CDROM/Disk1/setup.exe,看能否访问成功.
出于安全考虑最好不要直接下载*.exe文件,可以试着下载压缩后的文件,或用一个文本文件做测试,看看是否成功。
建议:WebRequest.KeepAlive = false;
同时得到后就马上关闭与释放连接与对象。