C downloads file instances synchronously and asynchronously

  • 2020-06-19 11:33:03
  • OfStack

1. Use HttpWebRequest/HttpWebResonse and WebClient


HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 
WebResponse response = request.GetResponse(); 
Stream stream = response.GetResponseStream();
if (!response.ContentType.ToLower().StartsWith("text/")) 
{ 
    //Value = SaveBinaryFile(response, FileName); 
    byte[] buffer = new byte[1024]; 
    Stream outStream = System.IO.File.Create(FileName); 
    Stream inStream = response.GetResponseStream();
    int l; 
    do 
    { 
        l = inStream.Read(buffer, 0, buffer.Length); 
        if (l > 0) 
            outStream.Write(buffer, 0, l); 
    } 
    while (l > 0);
    outStream.Close(); 
    inStream.Close(); 
}

2. Use WebClient


string url = "http://www.mozilla.org/images/feature-back-cnet.png"; 
WebClient myWebClient = new WebClient(); 
myWebClient.DownloadFile(url,"C:\\temp\\feature-back-cnet.png");

3. Asynchronous download example


        ///summary
        /// Asynchronous analysis download 
        ///summary
        private void AsyncAnalyzeAndDownload(string url, string savePath)
        {
            this.uriString = url;
            this.savePath = savePath;
            #region  Start of analysis timing 
            count = 0;
            count1 = 0;
            freq = 0;
            result = 0;
            QueryPerformanceFrequency(ref freq);
            QueryPerformanceCounter(ref count);
            #endregion
            using (WebClient wClient = new WebClient())
            {
                AutoResetEvent waiter = new AutoResetEvent(false);
                wClient.Credentials = CredentialCache.DefaultCredentials;
                wClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(AsyncURIAnalyze);
                wClient.DownloadDataAsync(new Uri(uriString), waiter);
                waiter.WaitOne();     Blocks the current thread until it is signaled 
            }

        }
        ///summary
        /// Asynchronous analysis 
        ///summary
        protected void AsyncURIAnalyze(Object sender, DownloadDataCompletedEventArgs e)
        {
            AutoResetEvent waiter = (AutoResetEvent)e.UserState;
            try
            {
                if (!e.Cancelled && e.Error == null)
                {

                    string dnDir = string.Empty;
                    string domainName = string.Empty;
                    string uri = uriString;
                     Get the domain name  [url]httpwww.sina.com[url]
                    Match match = Regex.Match(uri, @((http(s)))+[w-.]+[^]);, RegexOptions.IgnoreCase
                    domainName = match.Value;
                     Get the deepest directory of domain names  [url]httpwww.sina.commail[url]
                    if (domainName.Equals(uri))
                        dnDir = domainName;
                    else
                        dnDir = uri.Substring(0, uri.LastIndexOf(''));
                    dnDir += '';

                     To get the data 
                    string pageData = Encoding.UTF8.GetString(e.Result);
                    Liststring urlList = new Liststring();
                     Match full path 
                    match = Regex.Match(pageData, @((http(s)))+((()+[w-.]+()))+[w-.]+.+( + ImageType + )); , RegexOptions.IgnoreCase
                    while (match.Success)
                    {
                        string item = match.Value;
                         Short path processing 
                        if (item.IndexOf(http) == -1 && item.IndexOf(https) == -1)
                            item = (item[0] == ''  domainName  dnDir) + item;
                        if (!urlList.Contains(item))
                        {
                            urlList.Add(item);
                            imgUrlList.Add(item);
                             Real-time display of analysis results 
                            AddlbShowItem(item);
                             Download while analyzing 
                            WebRequest hwr = WebRequest.Create(item);
                            hwr.BeginGetResponse(new AsyncCallback(AsyncDownLoad), hwr);
                            hwr.Timeout = 0x30D40;         The default  0x186a0 - 100000 0x30D40 - 200000
                            hwr.Method = POST;
                            hwr.C;
                            hwr.MaximumAutomaticRedirections = 3;
                            hwr.Accept =imagegif, imagex-xbitmap, imagejpeg, imagepjpeg, applicationx-shockwave-flash, applicationvnd.ms-excel, applicationvnd.ms-powerpoint, applicationmsword, ;
                            hwr.Accept = imagegif, imagex-xbitmap, imagejpeg, imagepjpeg, ;
                            IAsyncResult iar = hwr.BeginGetResponse(new AsyncCallback(AsyncDownLoad), hwr);
                            iar.AsyncWaitHandle.WaitOne();
                        }
                        match = match.NextMatch();
                    }
                }
            }
            finally
            {
                waiter.Set();
                #region  End of analysis time 
                QueryPerformanceCounter(ref count1);
                count = count1 - count;
                result = (double)(count)  (double)freq;
                toolStripStatusLabel1.Text =  Analysis done! ;
                toolStripStatusLabel2.Text = string.Format(   Analysis of time consuming {0} seconds , result);
                Application.DoEvents();
                #endregion
                 After analysis of the 
                isAnalyzeComplete = true;
            }
        }
        /// <summary>
        ///  Asynchronous acceptance of data 
        /// </summary>
        /// <param name="asyncResult"></param>
        public  void AsyncDownLoad(IAsyncResult asyncResult)  
        {
            #region  Download start time 
            if (cfreq == 0)
            {
                QueryPerformanceFrequency(ref cfreq);
                QueryPerformanceCounter(ref ccount);
            }
            #endregion
            WebRequest request = (WebRequest)asyncResult.AsyncState;
            string url = request.RequestUri.ToString();
            try
            {
                WebResponse response = request.EndGetResponse(asyncResult);
                using (Stream stream = response.GetResponseStream())
                {
                    Image img = Image.FromStream(stream);
                    string[] tmpUrl = url.Split('.');
                    img.Save(string.Concat(savePath, "/", DateTime.Now.ToString("yyyyMMddHHmmssfff"), ".", tmpUrl[tmpUrl.Length - 1]));
                    img.Dispose();
                    stream.Close();
                }
                allDone.Set();
                // Delete downloaded images from the never downloaded list 
                imgUrlList.Remove(url);
                // Update list box 
                int indexItem = this.lbShow.Items.IndexOf(url);
                if (indexItem >= 0 && indexItem <= this.lbShow.Items.Count)
                    SetlbShowItem(indexItem);
            }
            catch (Exception)
            {
                imgUrlList.Remove(url);
            }
        }


Related articles: