c# 下载ZIP压缩包到指定的目录下

admin 2021-11-19 17:07:40 445浏览 0评论
        /// <summary>
        /// 下载ZIP压缩包到指定的目录下
        /// </summary>
        /// <param name="URL">下载的链接</param>
        /// <param name="filename">压缩包文件名,包含路径</param>
        /// <param name="prog">进度条</param>
        /// <param name="label1">进度百分比</param>
        /// <returns></returns>
        public bool DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
        {
            float percent = 0;
            try
            {
                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;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                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 * 50];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    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;
                    label1.Text = percent.ToString() + "%";
                    Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
                }
                so.Close();
                st.Close();
                return true;
            }
            catch (System.Exception)
            {
                return false;
                throw;
            }
        }



调用

            string str = System.Windows.Forms.Application.StartupPath + @"\NewVersions";
            if (!Directory.Exists(str)) Directory.CreateDirectory(str);

            zips = service.GetZips();
            string url = str + @"\" + zips[0];
            string DownUrl = service.GetUrl();
            bool flag = DownloadFile(DownUrl, url, this.progressBar1, label6);


0条评论