1、在window窗体加个button控件,双击进去
2、进入方法体中,编写方法
private void btnDownload_Click(object sender, EventArgs e)
{
DialogResult rs = MessageBox.Show("是否确定下载文件?", "系统提示", MessageBoxButtons.YesNo,MessageBoxIcon.Information);
if (rs == DialogResult.Yes)
{
MessageBox.Show("正在下载,请稍后。。。。。。");
string URL = "http://localhost:8088/CS_Dsp.zip"; //这个是服务器资源
string filename = @"D:\CS_Dsp.zip"; //这个下载到本地保存路径
//得到客户端请求的对象
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;
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;
so.Write(by, 0, osize);
osize = st.Read(by, 0, (int)by.Length);
}
so.Close();
st.Close();
MessageBox.Show("下载文件成功!");
}
else
{
MessageBox.Show("取消下载!");
}
}
3、点击下载文件进行测试
注意:前提在服务器url有你自己写的文件,才能下载下来