日期:2014-05-17 浏览次数:20801 次
class classDownloader { private string strURL; //待下载文件链接 private string strSavePath; //待下载文件存放路径 private long lContentLenth = 0; //文件的大小 private long lStartPos = 0; //文件下载的起始位置 private System.IO.FileStream fs; private System.IO.Stream ns; private System.Net.HttpWebRequest request; private System.Net.WebRequest req; private const int NBuff = 512;//下载流缓冲池大小 private void SetURL(string temp) //获取待下载文件链接 { strURL = temp; } private void SetSavePath(string temp) //获取待下载文件存放路径 { strSavePath = temp; } private void StartDownload() //开始下载 { //打开网络连接 try { // req = System.Net.HttpWebRequest.Create(strURL); // req.Method = "HEAD"; request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(strURL); System.Net.WebResponse resp = request.GetResponse(); long.TryParse(resp.Headers.Get("Content-Length"), out lContentLenth);//获取待下载文件的大小 //判断是新文件或续传文件或已经下好了 if (System.IO.File.Exists(strSavePath)) { fs = System.IO.File.OpenWrite(strSavePath); lStartPos = fs.Length; if (lStartPos >= lContentLenth) { MessageBox.Show("已经下好了"); return; } //lStartPos -= 10240; fs.Seek(lStartPos, System.IO.SeekOrigin.Current); } else { fs = new System.IO.FileStream(strSavePath, System.IO.FileMode.Create); lStartPos = 0; } if (lStartPos > 0) { request.AddRange((int)lStartPos); //设置range值 } //向服务器请求,获得服务器回应数据流 ns = request.GetResponse().GetResponseStream(); byte[] nbytes = new byte[NBuff]; int nReadSize = 0; nReadSize = ns.Read(nbytes, 0, NBuff); while (nReadSize > 0) { fs.Write(nbytes, 0, nReadSize); nReadSize = ns.Read(nbytes, 0, NBuff); Program.a.progressBar1.Value = (int)(((float)fs.Length / (float)lContentLenth) * 100); int resault = (int)((float)fs.Length / (float)lContentLenth*100); Program.a.label2.Text = "已下载" + resault+"%"; //Program.a.label2.Text = "已下载" + fs.Length + "/" + lContentLenth; } //MessageBox.Show("下载完成"); } catch (Exception ex) { MessageBox.Show("下载中出错" + ex.ToString()); } finally { if (!(lStartPos >= lContentLenth)) { ns.Close(); fs.Close(); } //req.Abort(); request.Abort(); } } public void update() { classWebRequest webrequest = new classWebRequest(); webrequest.WebReqVer(); /* DataSet dataset = new DataSet(); DataTable datatable = new DataTable("UpdataContext"); datatable.Columns.Add(new DataColumn ("No.",typeof (int)))