コード例 #1
0
        public static DownloadData Create(string url, string destFolder)
        {
            DownloadData downloadData = new DownloadData();
            WebRequest   req          = GetRequest(url);

            try
            {
                if (req is FtpWebRequest)
                {
                    // get the file size for FTP files
                    req.Method            = WebRequestMethods.Ftp.GetFileSize;
                    downloadData.response = req.GetResponse();
                    downloadData.GetFileSize();

                    // new request for downloading the FTP file
                    req = GetRequest(url);
                    downloadData.response = req.GetResponse();
                }
                else
                {
                    downloadData.response = req.GetResponse();
                    downloadData.GetFileSize();
                }
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Error downloading \"{0}\": {1}", url, e.Message), e);
            }

            // Check to make sure the response isn't an error. If it is this method
            // will throw exceptions.
            ValidateResponse(downloadData.response, url);

            // Take the name of the file given to use from the web server.
            string fileName = downloadData.response.Headers["Content-Disposition"];

            if (fileName != null)
            {
                int fileLoc = fileName.IndexOf("filename=", StringComparison.OrdinalIgnoreCase);

                if (fileLoc != -1)
                {
                    // go past "filename="
                    fileLoc += 9;

                    if (fileName.Length > fileLoc)
                    {
                        // trim off an ending semicolon if it exists
                        int end = fileName.IndexOf(';', fileLoc);

                        if (end == -1)
                        {
                            end = fileName.Length - fileLoc;
                        }
                        else
                        {
                            end -= fileLoc;
                        }

                        fileName = fileName.Substring(fileLoc, end).Trim();
                    }
                    else
                    {
                        fileName = null;
                    }
                }
                else
                {
                    fileName = null;
                }
            }

            if (string.IsNullOrEmpty(fileName))
            {
                // brute force the filename from the url
                fileName = Path.GetFileName(downloadData.response.ResponseUri.LocalPath);
            }

            // trim out non-standard filename characters
            if (!string.IsNullOrEmpty(fileName) && fileName.IndexOfAny(invalidFilenameChars.ToArray()) != -1)
            {
                //make a new string builder (with at least one bad character)
                StringBuilder newText = new StringBuilder(fileName.Length - 1);

                //remove the bad characters
                for (int i = 0; i < fileName.Length; i++)
                {
                    if (invalidFilenameChars.IndexOf(fileName[i]) == -1)
                    {
                        newText.Append(fileName[i]);
                    }
                }

                fileName = newText.ToString().Trim();
            }

            // if filename *still* is null or empty, then generate some random temp filename
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = Path.GetFileName(Path.GetTempFileName());
            }

            string downloadTo = Path.Combine(destFolder, fileName);

            downloadData.Filename = downloadTo;

            // If we don't know how big the file is supposed to be,
            // we can't resume, so delete what we already have if something is on disk already.
            if (!downloadData.IsProgressKnown && File.Exists(downloadTo))
            {
                File.Delete(downloadTo);
            }

            if (downloadData.IsProgressKnown && File.Exists(downloadTo))
            {
                // We only support resuming on http requests
                if (!(downloadData.Response is HttpWebResponse))
                {
                    File.Delete(downloadTo);
                }
                else
                {
                    // Try and start where the file on disk left off
                    downloadData.start = new FileInfo(downloadTo).Length;

                    // If we have a file that's bigger than what is online, then something
                    // strange happened. Delete it and start again.
                    if (downloadData.start > downloadData.size)
                    {
                        File.Delete(downloadTo);
                    }
                    else if (downloadData.start < downloadData.size)
                    {
                        // Try and resume by creating a new request with a new start position
                        downloadData.response.Close();
                        req = GetRequest(url);
                        ((HttpWebRequest)req).AddRange((int)downloadData.start);
                        downloadData.response = req.GetResponse();

                        if (((HttpWebResponse)downloadData.Response).StatusCode != HttpStatusCode.PartialContent)
                        {
                            // They didn't support our resume request.
                            File.Delete(downloadTo);
                            downloadData.start = 0;
                        }
                    }
                }
            }

            return(downloadData);
        }
コード例 #2
0
        // Begin downloading the file at the specified url, and save it to the given folder.
        void BeginDownload()
        {
            DownloadData data = null;
            FileStream   fs   = null;

            try
            {
                //start the stopwatch for speed calc
                sw.Start();

                // get download details
                waitingForResponse = true;
                data = DownloadData.Create(url, destFolder);
                waitingForResponse = false;

                //reset the adler
                downloadedAdler32.Reset();

                DownloadingTo = data.Filename;

                if (!File.Exists(DownloadingTo))
                {
                    // create the file
                    fs = File.Open(DownloadingTo, FileMode.Create, FileAccess.Write);
                }
                else
                {
                    // read in the existing data to calculate the adler32
                    if (Adler32 != 0)
                    {
                        GetAdler32(DownloadingTo);
                    }

                    // apend to an existing file (resume)
                    fs = File.Open(DownloadingTo, FileMode.Append, FileAccess.Write);
                }

                // create the download buffer
                byte[] buffer = new byte[BufferSize];

                int readCount;

                // update how many bytes have already been read
                sentSinceLastCalc = data.StartPoint; //for BPS calculation

                while ((readCount = data.DownloadStream.Read(buffer, 0, BufferSize)) > 0)
                {
                    // break on cancel
                    if (bw.CancellationPending)
                    {
                        data.Close();
                        fs.Close();
                        break;
                    }

                    // update total bytes read
                    data.StartPoint += readCount;

                    // update the adler32 value
                    if (Adler32 != 0)
                    {
                        downloadedAdler32.Update(buffer, 0, readCount);
                    }

                    // save block to end of file
                    fs.Write(buffer, 0, readCount);

                    //calculate download speed
                    calculateBps(data.StartPoint, data.TotalDownloadSize);

                    // send progress info
                    if (!bw.CancellationPending)
                    {
                        bw.ReportProgress(0, new object[] {
                            //use the realtive progress or the raw progress
                            UseRelativeProgress?
                            InstallUpdate.GetRelativeProgess(0, data.PercentDone) :
                                data.PercentDone,

                                // unweighted percent
                                data.PercentDone,
                                downloadSpeed, ProgressStatus.None, null
                        });
                    }

                    // break on cancel
                    if (bw.CancellationPending)
                    {
                        data.Close();
                        fs.Close();
                        break;
                    }
                }
            }
            catch (UriFormatException e)
            {
                throw new Exception(string.Format("Could not parse the URL \"{0}\" - it's either malformed or is an unknown protocol.", url), e);
            }
            catch (Exception e)
            {
                if (string.IsNullOrEmpty(DownloadingTo))
                {
                    throw new Exception(string.Format("Error trying to save file: {0}", e.Message), e);
                }
                else
                {
                    throw new Exception(string.Format("Error trying to save file \"{0}\": {1}", DownloadingTo, e.Message), e);
                }
            }
            finally
            {
                if (data != null)
                {
                    data.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
コード例 #3
0
        public static DownloadData Create(string url, string destFolder)
        {
            DownloadData downloadData = new DownloadData();
            WebRequest   request      = GetRequest(url);

            try
            {
                if (request is FtpWebRequest)
                {
                    request.Method        = "SIZE";
                    downloadData.response = request.GetResponse();
                    downloadData.GetFileSize();
                    request = GetRequest(url);
                    downloadData.response = request.GetResponse();
                }
                else
                {
                    downloadData.response = request.GetResponse();
                    downloadData.GetFileSize();
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Error downloading \"{url}\": {ex.Message}", ex);
            }
            ValidateResponse(downloadData.response, url);
            string text = downloadData.response.Headers["Content-Disposition"];

            if (text != null)
            {
                int num = text.IndexOf("filename=", StringComparison.OrdinalIgnoreCase);
                if (num != -1)
                {
                    num += 9;
                    if (text.Length > num)
                    {
                        int num2 = text.IndexOf(';', num);
                        num2 = ((num2 != -1) ? (num2 - num) : (text.Length - num));
                        text = text.Substring(num, num2).Trim();
                    }
                    else
                    {
                        text = null;
                    }
                }
                else
                {
                    text = null;
                }
            }
            if (string.IsNullOrEmpty(text))
            {
                text = Path.GetFileName(downloadData.response.ResponseUri.LocalPath);
            }
            if (!string.IsNullOrEmpty(text) && text.IndexOfAny(invalidFilenameChars.ToArray()) != -1)
            {
                StringBuilder stringBuilder = new StringBuilder(text.Length - 1);
                for (int i = 0; i < text.Length; i++)
                {
                    if (invalidFilenameChars.IndexOf(text[i]) == -1)
                    {
                        stringBuilder.Append(text[i]);
                    }
                }
                text = stringBuilder.ToString().Trim();
            }
            if (string.IsNullOrEmpty(text))
            {
                text = Path.GetFileName(Path.GetTempFileName());
            }
            string text2 = downloadData.Filename = Path.Combine(destFolder, text);

            if (!downloadData.IsProgressKnown && File.Exists(text2))
            {
                File.Delete(text2);
            }
            if (downloadData.IsProgressKnown && File.Exists(text2))
            {
                if (!(downloadData.Response is HttpWebResponse))
                {
                    File.Delete(text2);
                }
                else
                {
                    downloadData.start = new FileInfo(text2).Length;
                    if (downloadData.start > downloadData.size)
                    {
                        File.Delete(text2);
                    }
                    else if (downloadData.start < downloadData.size)
                    {
                        downloadData.response.Close();
                        request = GetRequest(url);
                        ((HttpWebRequest)request).AddRange((int)downloadData.start);
                        downloadData.response = request.GetResponse();
                        if (((HttpWebResponse)downloadData.Response).StatusCode != HttpStatusCode.PartialContent)
                        {
                            File.Delete(text2);
                            downloadData.start = 0L;
                        }
                    }
                }
            }
            return(downloadData);
        }
コード例 #4
0
ファイル: FileDownloader.cs プロジェクト: luckypal/Kiosk
        private void BeginDownload()
        {
            DownloadData downloadData = null;
            FileStream   fileStream   = null;

            try
            {
                sw.Start();
                waitingForResponse = true;
                downloadData       = DownloadData.Create(url, destFolder);
                waitingForResponse = false;
                downloadedAdler32.Reset();
                DownloadingTo = downloadData.Filename;
                if (!File.Exists(DownloadingTo))
                {
                    fileStream = File.Open(DownloadingTo, FileMode.Create, FileAccess.Write);
                }
                else
                {
                    if (Adler32 != 0)
                    {
                        GetAdler32(DownloadingTo);
                    }
                    fileStream = File.Open(DownloadingTo, FileMode.Append, FileAccess.Write);
                }
                byte[] buffer = new byte[4096];
                sentSinceLastCalc = downloadData.StartPoint;
                do
                {
                    int num;
                    if ((num = downloadData.DownloadStream.Read(buffer, 0, 4096)) <= 0)
                    {
                        return;
                    }
                    if (bw.CancellationPending)
                    {
                        downloadData.Close();
                        fileStream.Close();
                        return;
                    }
                    downloadData.StartPoint += num;
                    if (Adler32 != 0)
                    {
                        downloadedAdler32.Update(buffer, 0, num);
                    }
                    fileStream.Write(buffer, 0, num);
                    calculateBps(downloadData.StartPoint, downloadData.TotalDownloadSize);
                    if (!bw.CancellationPending)
                    {
                        bw.ReportProgress(0, new object[5]
                        {
                            UseRelativeProgress?InstallUpdate.GetRelativeProgess(0, downloadData.PercentDone) : downloadData.PercentDone,
                                downloadData.PercentDone,
                                downloadSpeed,
                                ProgressStatus.None,
                                null
                        });
                    }
                }while (!bw.CancellationPending);
                downloadData.Close();
                fileStream.Close();
            }
            catch (UriFormatException innerException)
            {
                throw new Exception($"Could not parse the URL \"{url}\" - it's either malformed or is an unknown protocol.", innerException);
            }
            catch (Exception ex)
            {
                if (string.IsNullOrEmpty(DownloadingTo))
                {
                    throw new Exception($"Error trying to save file: {ex.Message}", ex);
                }
                throw new Exception($"Error trying to save file \"{DownloadingTo}\": {ex.Message}", ex);
            }
            finally
            {
                downloadData?.Close();
                fileStream?.Close();
            }
        }
コード例 #5
0
        public static DownloadData Create(string url, string destFolder)
        {
            DownloadData downloadData = new DownloadData();
            WebRequest req = GetRequest(url);

            try
            {
                if (req is FtpWebRequest)
                {
                    // get the file size for FTP files
                    req.Method = WebRequestMethods.Ftp.GetFileSize;
                    downloadData.response = req.GetResponse();
                    downloadData.GetFileSize();

                    // new request for downloading the FTP file
                    req = GetRequest(url);
                    downloadData.response = req.GetResponse();
                }
                else
                {
                    downloadData.response = req.GetResponse();
                    downloadData.GetFileSize();
                }
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Error downloading \"{0}\": {1}", url, e.Message), e);
            }

            // Check to make sure the response isn't an error. If it is this method
            // will throw exceptions.
            ValidateResponse(downloadData.response, url);

            // Take the name of the file given to use from the web server.
            string fileName = downloadData.response.Headers["Content-Disposition"];

            if (fileName != null)
            {
                int fileLoc = fileName.IndexOf("filename=", StringComparison.OrdinalIgnoreCase);

                if (fileLoc != -1)
                {
                    // go past "filename="
                    fileLoc += 9;

                    if (fileName.Length > fileLoc)
                    {
                        // trim off an ending semicolon if it exists
                        int end = fileName.IndexOf(';', fileLoc);

                        if (end == -1)
                            end = fileName.Length - fileLoc;
                        else
                            end -= fileLoc;

                        fileName = fileName.Substring(fileLoc, end).Trim();
                    }
                    else
                        fileName = null;
                }
                else
                    fileName = null;
            }

            if (string.IsNullOrEmpty(fileName))
            {
                // brute force the filename from the url
                fileName = Path.GetFileName(downloadData.response.ResponseUri.LocalPath);
            }

            // trim out non-standard filename characters
            if (!string.IsNullOrEmpty(fileName) && fileName.IndexOfAny(invalidFilenameChars.ToArray()) != -1)
            {
                //make a new string builder (with at least one bad character)
                StringBuilder newText = new StringBuilder(fileName.Length - 1);

                //remove the bad characters
                for (int i = 0; i < fileName.Length; i++)
                {
                    if (invalidFilenameChars.IndexOf(fileName[i]) == -1)
                        newText.Append(fileName[i]);
                }

                fileName = newText.ToString().Trim();
            }

            // if filename *still* is null or empty, then generate some random temp filename
            if (string.IsNullOrEmpty(fileName))
                fileName = Path.GetFileName(Path.GetTempFileName());

            string downloadTo = Path.Combine(destFolder, fileName);

            downloadData.Filename = downloadTo;

            // If we don't know how big the file is supposed to be,
            // we can't resume, so delete what we already have if something is on disk already.
            if (!downloadData.IsProgressKnown && File.Exists(downloadTo))
                File.Delete(downloadTo);

            if (downloadData.IsProgressKnown && File.Exists(downloadTo))
            {
                // We only support resuming on http requests
                if (!(downloadData.Response is HttpWebResponse))
                {
                    File.Delete(downloadTo);
                }
                else
                {
                    // Try and start where the file on disk left off
                    downloadData.start = new FileInfo(downloadTo).Length;

                    // If we have a file that's bigger than what is online, then something 
                    // strange happened. Delete it and start again.
                    if (downloadData.start > downloadData.size)
                        File.Delete(downloadTo);
                    else if (downloadData.start < downloadData.size)
                    {
                        // Try and resume by creating a new request with a new start position
                        downloadData.response.Close();
                        req = GetRequest(url);
                        ((HttpWebRequest)req).AddRange((int)downloadData.start);
                        downloadData.response = req.GetResponse();

                        if (((HttpWebResponse)downloadData.Response).StatusCode != HttpStatusCode.PartialContent)
                        {
                            // They didn't support our resume request. 
                            File.Delete(downloadTo);
                            downloadData.start = 0;
                        }
                    }
                }
            }

            return downloadData;
        }