Exemplo n.º 1
0
        /// <summary>
        /// Begin downloading the file at the specified url, and save it to the given folder.
        /// </summary>
        public void Download(string url, string destFolder)
        {
            DownloadData data = null;

            this.canceled = false;

            try
            {
                // get download details
                data = DownloadData.Create(url, destFolder, this.proxy);
                // Find out the name of the file that the web server gave us.
                string destFileName = Path.GetFileName(data.Response.ResponseUri.ToString());


                // The place we're downloading to (not from) must not be a URI,
                // because Path and File don't handle them...
                destFolder         = destFolder.Replace("file:///", "").Replace("file://", "");
                this.downloadingTo = Path.Combine(destFolder, destFileName);

                // Create the file on disk here, so even if we don't receive any data of the file
                // it's still on disk. This allows us to download 0-byte files.
                if (!File.Exists(downloadingTo))
                {
                    FileStream fs = File.Create(downloadingTo);
                    fs.Close();
                }

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

                int readCount;

                // update how many bytes have already been read
                long totalDownloaded = data.StartPoint;

                bool gotCanceled = false;

                while ((int)(readCount = data.DownloadStream.Read(buffer, 0, downloadBlockSize)) > 0)
                {
                    // break on cancel
                    if (canceled)
                    {
                        gotCanceled = true;
                        data.Close();
                        break;
                    }

                    // update total bytes read
                    totalDownloaded += readCount;

                    // save block to end of file
                    SaveToFile(buffer, readCount, this.downloadingTo);

                    // send progress info
                    if (data.IsProgressKnown)
                    {
                        RaiseProgressChanged(totalDownloaded, data.FileSize);
                    }

                    // break on cancel
                    if (canceled)
                    {
                        gotCanceled = true;
                        data.Close();
                        break;
                    }
                }

                if (!gotCanceled)
                {
                    OnDownloadComplete();
                }
            }
            catch (UriFormatException e)
            {
                throw new ArgumentException(
                          String.Format("Could not parse the URL \"{0}\" - it's either malformed or is an unknown protocol.", url), e);
            }
            finally
            {
                if (data != null)
                {
                    data.Close();
                }
            }
        }
Exemplo n.º 2
0
        public static DownloadData Create(string url, string destFolder, IWebProxy proxy)
        {
            // This is what we will return
            DownloadData downloadData = new DownloadData();

            downloadData.proxy = proxy;

            long urlSize = downloadData.GetFileSize(url);

            downloadData.size = urlSize;

            WebRequest req = downloadData.GetRequest(url);

            try
            {
                downloadData.response = (WebResponse)req.GetResponse();
            }
            catch (Exception e)
            {
                throw new ArgumentException(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 = System.IO.Path.GetFileName(downloadData.response.ResponseUri.ToString());

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

            // 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 > urlSize)
                    {
                        File.Delete(downloadTo);
                    }
                    else if (downloadData.start < urlSize)
                    {
                        // Try and resume by creating a new request with a new start position
                        downloadData.response.Close();
                        req = downloadData.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);
        }
Exemplo n.º 3
0
        public static DownloadData Create(string url, string hostname, string destFileName, int timeout)
        {
            // This is what we will return
            DownloadData downloadData = new DownloadData();

            downloadData.downloadTo = destFileName;

            long urlSize = downloadData.GetFileSize(url, hostname, timeout);

            downloadData.size = urlSize;

            WebRequest req = downloadData.GetRequest(url, timeout);

            try
            {
                downloadData.response = (WebResponse)req.GetResponse();
            }
            catch (Exception e)
            {
                throw new ArgumentException(String.Format(
                                                "Error downloading \"{0}\": {1}", url, e.Message), e);
            }

            String lastModified = downloadData.response.Headers["Last-Modified"] ?? "";

            // 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 = System.IO.Path.GetFileName(downloadData.response.ResponseUri.ToString());

            //String downloadTo = Path.Combine(destFileName, fileName);

            String downloadTo = destFileName;

            FingerPrint fingerPrint = LoadFingerPrint(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 ||
                fingerPrint.timeStamp != lastModified ||
                fingerPrint.fileSize != urlSize)
            {
                DeleteDestFile(downloadTo);
            }

            SaveFingerPrint(downloadTo, new FingerPrint {
                timeStamp = lastModified, fileSize = urlSize
            });

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

                    if (downloadData.start < urlSize)
                    {
                        // Try and resume by creating a new request with a new start position
                        downloadData.response.Close();
                        req = downloadData.GetRequest(url, timeout);
                        ((HttpWebRequest)req).AddRange((int)downloadData.start);
                        downloadData.response = req.GetResponse();

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

//                         if (req != null)        //销毁request
//                         {
//                             req.Abort();
//                             req = null;
//                         }
                    }
                }
            }

            downloadData.downloadToStream = File.Open(downloadTo, FileMode.Append, FileAccess.Write);

            return(downloadData);
        }
Exemplo n.º 4
0
        ///// <summary>
        ///// Begin downloading the file at the specified url, and save it to the current fileName.
        ///// </summary>
        //public void Download(string url)
        //{
        //    Download(url, "");
        //}
        /// <summary>
        /// Begin downloading the file at the specified url, and save it to the given fileName.
        /// </summary>
        public void Download(string url, string hostName, string destFileName, int timeout)
        {
            DownloadData data = null;

            this.canceled = false;

            try
            {
                // get download details
                data = DownloadData.Create(url, hostName, destFileName, timeout);
                //// Find out the name of the file that the web server gave us.
                //string destFileName = Path.GetFileName(data.Response.ResponseUri.ToString());

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

                int readCount;

                // update how many bytes have already been read
                long totalDownloaded = data.StartPoint;

                bool gotCanceled = false;

                while ((int)(readCount = data.DownloadStream.Read(buffer, 0, downloadBlockSize)) > 0)
                {
                    // break on cancel
                    if (this.canceled)
                    {
                        gotCanceled = true;
                        break;
                    }

                    // update total bytes read
                    totalDownloaded += readCount;

                    // save block to end of file
                    SaveToFile(buffer, readCount, data.DownloadingToStream);

                    // send progress info
                    if (data.IsProgressKnown)
                    {
                        RaiseProgressChanged(totalDownloaded, data.FileSize);
                    }

                    // break on cancel
                    if (this.canceled)
                    {
                        gotCanceled = true;
                        break;
                    }
                }

                // stream could be incomplete
                if (data.IsProgressKnown)
                {
                    if (totalDownloaded < data.FileSize)
                    {
                        throw new WebException("date transfer not completed", WebExceptionStatus.ConnectionClosed);
                    }
                }

                if (!gotCanceled)
                {
                    RaiseProgressChanged(data.FileSize, data.FileSize);
                    data.CleanOnFinish();
                    OnDownloadComplete();
                }
            }
            catch (UriFormatException e)
            {
                throw new ArgumentException(
                          String.Format("Could not parse the URL \"{0}\" - it's either malformed or is an unknown protocol.", url), e);
            }
            finally
            {
                if (data != null)
                {
                    data.Close();
                }
            }
        }
Exemplo n.º 5
0
        public static DownloadData Create(string url, string destFileName, IWebProxy proxy, Int32 timeout)
        {

            // This is what we will return
            DownloadData downloadData = new DownloadData();
            downloadData.proxy = proxy;
			downloadData.timeout = timeout;
			downloadData.downloadTo = destFileName;

            long urlSize = downloadData.GetFileSize(url);
            downloadData.size = urlSize;

            WebRequest req = downloadData.GetRequest(url);
            try
            {
                downloadData.response = (WebResponse)req.GetResponse();
            }
            catch (Exception e)
            {
                throw new ArgumentException(String.Format(
                    "Error downloading \"{0}\": {1}", url, e.Message), e);
            }

			String lastModified = downloadData.response.Headers["Last-Modified"] ?? "";

            // 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 = System.IO.Path.GetFileName(downloadData.response.ResponseUri.ToString());

			//String downloadTo = Path.Combine(destFileName, fileName);

			String downloadTo = destFileName;

			FingerPrint fingerPrint = LoadFingerPrint(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
				|| fingerPrint.timeStamp != lastModified
				|| fingerPrint.fileSize != urlSize)
			{
				DeleteDestFile(downloadTo);
			}

			SaveFingerPrint(downloadTo, new FingerPrint { timeStamp = lastModified, fileSize = urlSize });

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

                    if (downloadData.start < urlSize)
                    {
                        // Try and resume by creating a new request with a new start position
                        downloadData.response.Close();
                        req = downloadData.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. 
                            DeleteDestFile(downloadTo);
                            downloadData.start = 0;
                        }
                    }
                }
            }

			downloadData.downloadToStream = File.Open(downloadTo, FileMode.Append, FileAccess.Write);

            return downloadData;
        }