C#从服务器下载文件到客户端源码
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有你自己寫的文件,才能下載下來
總結
以上是生活随笔為你收集整理的C#从服务器下载文件到客户端源码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle 表类型变量的使用
- 下一篇: c# datagridview表格控件常