利用HttpWebRequest下载资源

 private void DownLoadFile()
        {
            HttpWebRequest httpWebReq = (HttpWebRequest)WebRequest.Create(address);
            httpWebReq.Method = WebRequestMethods.Http.Get;
            HttpWebResponse httpWebResp = (HttpWebResponse)httpWebReq.GetResponse();
            long contentLength = httpWebResp.ContentLength;
            this.progressBar1.Maximum = int.Parse(contentLength.ToString());

            //设置临时文件名
            string tempFileName = fileName + ".tempdl";
            //string cfgFileName = fileName + ".tempdlcfg";
            FileInfo fi = new FileInfo(tempFileName);
            if (fi.Exists)
            {
                //日后断点续传[暂时不做]
                //直接删除存在
                fi.Delete();
            }
            try
            {
                //创建临时文件 
                using (FileStream fs = fi.Create())
                {
                    fs.SetLength(contentLength);
                    //获取响应流
                    using (Stream respstm = httpWebResp.GetResponseStream())
                    {
                        if (respstm.CanRead)
                        {
                            Byte[] buffer = new byte[1024];
                            //读取数据到缓冲
                            int length = respstm.Read(buffer, 0, buffer.Length);
                            //设置进度条直
                            this.SetProgressBar(length);
                            while (length > 0)
                            {
                                //将网络流写入本地
                                fs.Write(buffer, 0, length);
                                //继续读取
                                length = respstm.Read(buffer, 0, buffer.Length);

                                //断点续传配置文件
                                //using (FileStream cfgfs = new FileStream(cfgFileName, FileMode.CreateNew))
                                //{
                                //    cfgfs.Write()
                                //}

                                //设置进度条信息
                                //this.SetProgressBar(length);
                            }
                        }
                        //写配置文件
                        //FileInfo fik12cfg = new FileInfo();
                    }
                }
                //this.ReNameApp(fi, fileName);
                //this.RunAtApp(fileName);
            }
            catch
            { }
        }

上一篇:课后自主练习(高精度)1082. 猜猜猜 naive《编程思维与实践》个人学习笔记


下一篇:Vue3和Electron实现桌面端应用