欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#同步、異步遠(yuǎn)程下載文件實例

 更新時間:2014年04月23日 11:40:44   作者:  
使用C#下載一個Internet上的文件主要是依靠HttpWebRequest/HttpWebResonse和WebClient。具體處理起來還有同步和異步兩種方式,所以我們其實有四種組合

1、使用HttpWebRequest/HttpWebResonse和WebClient

復(fù)制代碼 代碼如下:

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

復(fù)制代碼 代碼如下:

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、異步下載例子

復(fù)制代碼 代碼如下:

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

        }

        ///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 += '';

                    獲取數(shù)據(jù)
                    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);

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

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

                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>
        /// 異步接受數(shù)據(jù)
        /// </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();

                //從未下載的列表中刪除已經(jīng)下載的圖片
                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);
            }
        }

相關(guān)文章

  • C#連接Oracle數(shù)據(jù)庫的實例方法

    C#連接Oracle數(shù)據(jù)庫的實例方法

    C#連接Oracle數(shù)據(jù)庫的實例方法,需要的朋友可以參考一下
    2013-04-04
  • 關(guān)于C# Math 處理奇進(jìn)偶不進(jìn)的實現(xiàn)代碼

    關(guān)于C# Math 處理奇進(jìn)偶不進(jìn)的實現(xiàn)代碼

    下面小編就為大家?guī)硪黄P(guān)于C# Math 處理奇進(jìn)偶不進(jìn)的實現(xiàn)代碼。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-05-05
  • 詳解C#中三個關(guān)鍵字params,Ref,out

    詳解C#中三個關(guān)鍵字params,Ref,out

    本文主要討論params關(guān)鍵字,ref關(guān)鍵字,out關(guān)鍵字。非常不錯,具有參考借鑒價值,需要的朋友參考下吧
    2017-05-05
  • 淺談C# async await 死鎖問題總結(jié)

    淺談C# async await 死鎖問題總結(jié)

    這篇文章主要介紹了淺談C# async await 死鎖問題總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • 操作xml,將xml數(shù)據(jù)顯示到treeview的C#代碼

    操作xml,將xml數(shù)據(jù)顯示到treeview的C#代碼

    這篇文章主要介紹了操作xml,將xml數(shù)據(jù)顯示到treeview的C#代碼,有需要的朋友可以參考一下
    2013-11-11
  • c# 網(wǎng)絡(luò)編程之http

    c# 網(wǎng)絡(luò)編程之http

    這篇文章主要介紹了c# 提供一個HTTP服務(wù)的實現(xiàn)示例,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下
    2021-02-02
  • c#如何實現(xiàn)接口事件

    c#如何實現(xiàn)接口事件

    這篇文章主要介紹了c#如何實現(xiàn)接口事件,幫助大家更好的理解和學(xué)習(xí)c#,感興趣的朋友可以了解下
    2020-10-10
  • C#導(dǎo)出Excel的方法

    C#導(dǎo)出Excel的方法

    本文給大家分享的是基于.net 1.0開發(fā)的程序如何實現(xiàn)導(dǎo)出Excel的方法和示例,使用的是UltraWebGrid自帶導(dǎo)出Excel的控件,非常的簡單實用,有需要的小伙伴可以參考下。
    2015-06-06
  • windows系統(tǒng)下,如何在C#程序中自動安裝字體

    windows系統(tǒng)下,如何在C#程序中自動安裝字體

    在Windows系統(tǒng)中,原有自帶的字體樣式有限,有時候我們的程序會使用到個別稀有或系統(tǒng)不自帶的字體。因此我們需要將字體打包到程序中,當(dāng)程序啟動時,檢測系統(tǒng)是否有該字體,如果沒有則安裝該字體,也可以動態(tài)加載字體。
    2020-11-11
  • DOTNETBAR制作圓角窗體和圓角控件代碼實例

    DOTNETBAR制作圓角窗體和圓角控件代碼實例

    這篇文章主要介紹了DOTNETBAR制作圓角窗體和圓角控件的方法,大家參考使用吧
    2013-11-11

最新評論