using System.IO; using System.Text; using System.Net;
按钮事件:
private void button5_Click(object sender, System.EventArgs e) { string DownloadUrl=" "; string LocalPath=Application.StartupPath.ToString()+"\\"+"qqwry"+DateTime.Now.ToShortDateString()+".rar";
if(downfile(DownloadUrl,LocalPath)) { MessageBox.Show("下载完成"); } else { MessageBox.Show("下载过程中出现错误:"); }
}
下载函数: public bool downfile(string url,string LocalPath) { try { Uri u = new Uri(url); HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u); mRequest.Method = "GET"; mRequest.ContentType = "application/x-www-form-urlencoded"; HttpWebResponse wr = (HttpWebResponse)mRequest.GetResponse(); statusBar1.Text = "开始下载文件..."; Stream sIn = wr.GetResponseStream(); FileStream fs = new FileStream(LocalPath, FileMode.Create, FileAccess.Write); long length = wr.ContentLength; int i = 0; long j=0; statusBar1.Text = "正在接收数据..."; byte[] buffer = new byte[1024]; while ((i = sIn.Read(buffer, 0, buffer.Length)) > 0) { j+=i; fs.Write(buffer, 0,i); statusBar1.Text="文件大小:"+length.ToString()+"字节 当前下载:"+j+"字节"; }
sIn.Close(); wr.Close(); statusBar1.Text = "文件下载完毕...文件大小"+fs.Length.ToString()+"字节"; fs.Close(); return true; } catch { return false; }
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xqf222/archive/2007/09/19/1790830.aspx
|
请发表评论