国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#同步、異步遠程下載文件實例

2020-01-24 02:41:33
字體:
來源:轉載
供稿:網友

1、使用HttpWebRequest/HttpWebResonse和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、使用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、異步下載例子

復制代碼 代碼如下:

        ///summary
        ///異步分析下載
        ///summary
        private void AsyncAnalyzeAndDownload(string url, string savePath)
        {
            this.uriString = url;
            this.savePath = savePath;

            #region 分析計時開始

            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();    阻止當前線程,直到收到信號
            }

        }

        ///summary
        ///異步分析
        ///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;

                    獲得域名 [url]httpwww.sina.com[url]
                    Match match = Regex.Match(uri, @((http(s)))+[w-.]+[^]);, RegexOptions.IgnoreCase
                    domainName = match.Value;

                    獲得域名最深層目錄 [url]httpwww.sina.commail[url]
                    if (domainName.Equals(uri))
                        dnDir = domainName;
                    else
                        dnDir = uri.Substring(0, uri.LastIndexOf(''));

                    dnDir += '';

                    獲取數據
                    string pageData = Encoding.UTF8.GetString(e.Result);
                    Liststring urlList = new Liststring();

                    匹配全路徑
                    match = Regex.Match(pageData, @((http(s)))+((()+[w-.]+()))+[w-.]+.+( + ImageType + )); , RegexOptions.IgnoreCase
                    while (match.Success)
                    {
                        string item = match.Value;
                        短路徑處理
                        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);

                            實時顯示分析結果
                            AddlbShowItem(item);

                            邊分析邊下載
                            WebRequest hwr = WebRequest.Create(item);
                            hwr.BeginGetResponse(new AsyncCallback(AsyncDownLoad), hwr);
                            hwr.Timeout = 0x30D40;        默認 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 分析計時結束

                QueryPerformanceCounter(ref count1);
                count = count1 - count;
                result = (double)(count)  (double)freq;

                toolStripStatusLabel1.Text = 分析完畢!;
                toolStripStatusLabel2.Text = string.Format(  分析耗時{0}秒, result);
                Application.DoEvents();

                #endregion

                分析完畢
                isAnalyzeComplete = true;
            }
        }

        /// <summary>
        /// 異步接受數據
        /// </summary>
        /// <param name="asyncResult"></param>
        public  void AsyncDownLoad(IAsyncResult asyncResult) 
        {
            #region 下載計時開始

            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();

                //從未下載的列表中刪除已經下載的圖片
                imgUrlList.Remove(url);

                //更新列表框
                int indexItem = this.lbShow.Items.IndexOf(url);
                if (indexItem >= 0 && indexItem <= this.lbShow.Items.Count)
                    SetlbShowItem(indexItem);
            }
            catch (Exception)
            {
                imgUrlList.Remove(url);
            }
        }

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 台东市| 卢湾区| 曲沃县| 额敏县| 盖州市| 名山县| 称多县| 旬阳县| 木兰县| 甘孜县| 丰镇市| 安达市| 轮台县| 偃师市| 阳曲县| 石河子市| 从化市| 江城| 蓬安县| 通海县| 郁南县| 友谊县| 遵义市| 万宁市| 霍林郭勒市| 大英县| 托克托县| 鹤山市| 龙胜| 棋牌| 沂水县| 北碚区| 商城县| 东源县| 西安市| 福建省| 金山区| 大余县| 麻栗坡县| 长治县| 绥滨县|