webclientを使ってダウンロードの実例をアップロードします.

22909 ワード

http://blog.csdn.net/kevonz/article/details/5078432

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Net;

using System.IO;

 

namespace The9web.Com

{

    class UpDownLoadFile

    {

 

        /// <summary>

        /// WebClient        (     )

        /// </summary>

        /// <param name="fileNameFullPath">      (     )</param>

        /// <param name="strUrlDirPath">Web        </param>

        /// <returns>True/False      </returns>

        public bool UpLoadFile(string fileNameFullPath, string strUrlDirPath)

        {

            //           

            string fileName = fileNameFullPath.Substring(fileNameFullPath.LastIndexOf("//") + 1);

            //                

            string NewFileName = DateTime.Now.ToString("yyyyMMddhhmmss")

                                        + DateTime.Now.Millisecond.ToString()

                                        + fileNameFullPath.Substring(fileNameFullPath.LastIndexOf("."));

            //       

            string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);

            if (strUrlDirPath.EndsWith("/") == false) strUrlDirPath = strUrlDirPath + "/";

            //        ,     (     )

            strUrlDirPath = strUrlDirPath + NewFileName;

            //   WebClient  

            WebClient myWebClient = new WebClient();

            myWebClient.Credentials = CredentialCache.DefaultCredentials;

            //               

            FileStream myFileStream = new FileStream(fileNameFullPath, FileMode.Open, FileAccess.Read);

            BinaryReader myBinaryReader = new BinaryReader(myFileStream);

            try

            {

                byte[] postArray = myBinaryReader.ReadBytes((int)myFileStream.Length);

                //    Web  ,      

                Stream postStream = myWebClient.OpenWrite(strUrlDirPath, "PUT");

                if (postStream.CanWrite)

                {

                    postStream.Write(postArray, 0, postArray.Length);

                }

                else

                {

                    //MessageBox.Show("Web           ,   Web         !","    ",MessageBoxButtons.OK,MessageBoxIcon.Information);

                }

                postStream.Close();//   

                return true;

            }

            catch (Exception exp)

            {

                //MessageBox.Show("      :" + exp.Message, "    ", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return false;

            }

        }

 

        /// <summary>

        ///            (     )

        /// </summary>

        /// <param name="strUrlFilePath">    Web         (     :http://www.the9web.com/test.rar</param>

        /// <param name="Dir">      (    ,       )</param>

        /// <returns>True/False      </returns>

        public bool DownLoadFile(string strUrlFilePath, string strLocalDirPath)

        {

            //   WebClient  

            WebClient client = new WebClient();

            //       

            string fileName = strUrlFilePath.Substring(strUrlFilePath.LastIndexOf("/"));

            //

            string Path = strLocalDirPath + fileName;

            try

            {

                WebRequest myWebRequest = WebRequest.Create(strUrlFilePath);

            }

            catch (Exception exp)

            {

                MessageBox.Show("" + exp.Message, "    ", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            try

            {

                client.DownloadFile(strUrlFilePath, Path);

                return true;

            }

            catch (Exception exp)

            {

                MessageBox.Show("" + exp.Message, "    ", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return false;

            }

        }

 

 

        /// <summary>

        ///         (     )

        /// </summary>

        /// <param name="URL">  </param>

        /// <param name="Filename">   </param>

        /// <param name="Prog">     ProgressBar</param>

        /// <returns>True/False      </returns>

        public bool DownLoadFile(string URL, string Filename, ProgressBar Prog)

        {

            try

            {

                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); // URL      WEB     

                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); // WEB    WEB     

                long totalBytes = myrp.ContentLength; // WEB           

                Prog.Maximum = (int)totalBytes; //                 

                System.IO.Stream st = myrp.GetResponseStream(); // WEB     ( )   

                System.IO.Stream so = new System.IO.FileStream(Filename, System.IO.FileMode.Create); //     ( )   

                long totalDownloadedByte = 0; //         

                byte[] by = new byte[1024];

                int osize = st.Read(by, 0, (int)by.Length); //     

                while (osize > 0)

                {

                    totalDownloadedByte = osize + totalDownloadedByte; //         

                    Application.DoEvents();

                    so.Write(by, 0, osize); //     

                    Prog.Value = (int)totalDownloadedByte; //        

                    osize = st.Read(by, 0, (int)by.Length); //     

                }

                so.Close(); //   

                st.Close(); //   

                return true;

            }

            catch

            {

                return false;

            }

        }

 

 

        /// <summary>

        ///         (       )

        /// </summary>

        /// <param name="URL">  </param>

        /// <param name="Filename">   </param>

        /// <param name="Prog">       ToolStripProgressBar</param>

        /// <returns>True/False      </returns>

        public bool DownLoadFile(string URL, string Filename, ToolStripProgressBar Prog)

        {

            try

            {

                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); // URL      WEB     

                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); // WEB    WEB     

                long totalBytes = myrp.ContentLength; // WEB           

                Prog.Maximum = (int)totalBytes; //                 

                System.IO.Stream st = myrp.GetResponseStream(); // WEB     ( )   

                System.IO.Stream so = new System.IO.FileStream(Filename, System.IO.FileMode.Create); //     ( )   

                long totalDownloadedByte = 0; //         

                byte[] by = new byte[1024];

                int osize = st.Read(by, 0, (int)by.Length); //     

                while (osize > 0)

                {

                    totalDownloadedByte = osize + totalDownloadedByte; //         

                    Application.DoEvents();

                    so.Write(by, 0, osize); //     

                    Prog.Value = (int)totalDownloadedByte; //        

                    osize = st.Read(by, 0, (int)by.Length); //     

                }

                so.Close(); //      

                st.Close(); //      

                return true;

            }

            catch

            {

                return false;

            }

 

        }

 

    }

}
View Code
WebClientはもう一つの非常にクールな特性がありますが、残念ながら公式の助けは言及されていません.WebCientはブラウザとキャッシュファイルを共有できます.具体的には、ウェブブラウズを通じてキャッシュされたファイルがあれば、WebClientでこのファイルをダウンロードすると、WebClientはキャッシュファイルから直接読み取り、再ダウンロードしない.逆もまた、WebClientがダウンロードしたファイルはブラウザキャッシュディレクトリに保存されています.ブラウザとWebClientは次回使用します.これはsilverlightダイナミックダウンロードとキャッシュを実現する理論的な基礎です.とても重要です.
 
もちろん開発者がキャッシュファイルを使いたくない時もあります.例えば、サーバーファイルが更新されました.キャッシュのファイルではなく、最新のファイルをダウンロードしたいです.このような状況はどう処理しますか?ファイルキャッシュはurlに基づいているので、urlの後ろにランダムな無意味な文字を加えると、例えば?o=123はキャッシュを迂回することができます.欠点はダウンロードするたびに新しいキャッシュファイルが追加され、空きがなくなることです.
 
 
WebCientを使ってファイルのダウンロードを実現します.
http://blog.sina.com.cn/s/blog_6 e 51 df 7 f 0100 sw 6 t.