下载文件,进度展示

发布时间 2023-03-22 21:16:00作者: 安静点--
  private Stopwatch _downloadStopWatch = _downloadStopWatch = new Stopwatch();
    private bool WebClientDownloadInstallerFile(string url, string fileName, double filelength)
        {
            DateTime startTime = DateTime.Now;

            string folderPath = fileName.Substring(0, fileName.LastIndexOf("\\"));
            if (!Directory.Exists(folderPath))
            {
                //新建文件夹
                Directory.CreateDirectory(folderPath);
            }
            bool resumeDownload = IsResume(url, fileName);
            string tempFileName = fileName + ".temp";
            bool isDownloadSuccessfully = false;
            FileMode fm = FileMode.Create;
            Stream stream = null;
            FileStream fileStream = null;
            long resumDownload = 0;
            HttpWebResponse response = null;
            this._downloadStopWatch.Start();
            try
            {
                Uri installerUrl = new Uri(url);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
                if (resumeDownload)
                {
                    FileInfo fn = new FileInfo(tempFileName);
                    httpWebRequest.AddRange(fn.Length);
                    //httpWebRequest.Headers.Add("range",fn.Length.ToString());
                    resumDownload = fn.Length;
                    fm = FileMode.Append;
                }

                response = (HttpWebResponse)httpWebRequest.GetResponse();
                stream = response.GetResponseStream();

                double contentLength = DownloadManager.GetContentLength(response);
                if (contentLength <= 0)
                {
                    if (filelength <= 0)
                    {
                        filelength = response.ContentLength;
                    }
                    else
                    {
                        contentLength = filelength;
                    }
                }

                byte[] buffer = new byte[BufferSize];
                long downloadedLength = 0;
                int currentDataLength;
                if (resumeDownload)
                {
                    FileInfo fn = new FileInfo(tempFileName);
                    downloadedLength = fn.Length;
                }
                fileStream = new FileStream(tempFileName, fm);

                while ((currentDataLength = stream.Read(buffer, 0, BufferSize)) > 0 && !this._cancelDownload)
                {
                    fileStream.Write(buffer, 0, currentDataLength);
                    downloadedLength += (long)currentDataLength;
                    TimeSpan span = DateTime.Now - startTime;
                    double second = span.TotalSeconds;
                    string spead = "";
                    if (second > 0.001)
                    {
                        spead = ((downloadedLength - resumDownload) / 1024 / second).ToString("0.00") + "KB/秒";
                    }
                    //每一秒
                    if (this._downloadStopWatch.ElapsedMilliseconds > 1000)
                    {
                        this._downloadStopWatch.Reset();
                        this._downloadStopWatch.Start();

                        double doubleDownloadPersent = 0.0;
                        if (contentLength > 0.0)
                        {
                            doubleDownloadPersent = (double)downloadedLength / contentLength;
                            if (doubleDownloadPersent > 1.0)
                            {
                                doubleDownloadPersent = 1.0;
                            }
                        }

                        int intDownloadPersent = (int)(doubleDownloadPersent * 100);

                        double len = contentLength - downloadedLength;
                        double seconds = len / (downloadedLength / second);

                        DownloadInfo info = new DownloadInfo()
                        {
                            Message = "xxx",
                            Persent = intDownloadPersent,
                            Spead = spead,
                            RemainingTime = TimeSpan.FromSeconds(seconds).ToString("g").Substring(0, 8)
                        };

                        DownloadingStatusChanged(info);
                    }
                }

                if (this._cancelDownload)
                {
                    DownloadInfo info = new DownloadInfo() { Message = "已取消下载", Persent = 100 };
                    DownloadingStatusChanged(info);
                    isDownloadSuccessfully = false;
                }
                else if (currentDataLength >= 0)
                {
                    isDownloadSuccessfully = true;
                }
            }
            catch (Exception ex)
            { 
                isDownloadSuccessfully = false;
            }
            finally
            {
                this._downloadStopWatch.Stop();
                if (fileStream != null)
                {
                    fileStream.Flush();
                    fileStream.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }

                if (response != null)
                {
                    response.Close();
                }
            }
            if (isDownloadSuccessfully)
            {
                if (File.Exists(fileName))
                {
                    Util.DeleteFileIfExists(fileName);
                }
               
                File.Move(tempFileName, fileName);

                string tempFileInfoName = fileName + ".temp.info";
                if (File.Exists(tempFileInfoName))
                {
                    Util.DeleteFileIfExists(tempFileInfoName);
                }
            }
            return isDownloadSuccessfully;
        }