C#本地文件下載以及FTP文件服務下載(以Pdf文件爲例)

1、C#實現本地文件下載函數

一、文件下載的路徑  文件名稱 以及文件下載以後要放的位置  這三個變量是必需要的spa

二、定義如下四個對象:日誌

       FileWebRequest ftpWebRequest = null;
        FileWebResponse ftpWebResponse = null;
        Stream ftpResponseStream = null;
        FileStream outputStream = null;對象

三、建立文件下載存放位置的路徑(不須要手動建立,若是路徑存在就建立 不存在就不建立)字符串

      Directory.CreateDirectory(LocalFolder);//建立文件夾名稱get

     * 這裏提一點  Path.Combine()這個就是文件路徑拼接的函數,會自動判斷,在須要的文件加  \\  string

    好比 string filePath=  Path.Combine(「D:」,「test」,"download");  //  filePath="D:\\test\download";it

四、  而後執行如下代碼  便可完成文件下載io

           ftpWebRequest = (FileWebRequest)FileWebRequest.Create(new Uri(uri));
            ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            ftpWebResponse = (FileWebResponse)ftpWebRequest.GetResponse();
            ftpResponseStream = ftpWebResponse.GetResponseStream();
            long contentLength = ftpWebResponse.ContentLength;
            int bufferSize = 2048;
            byte[] buffer = new byte[bufferSize];
            int readCount;
            readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
            }class

五、代碼寫完以後要思考,下載文件的時候如何出現異常  這時在整個代碼加個 Try{} catch{}

具體代碼以下:

     public static void Main(string[] args)
        {
            TestFile tf = new TestFile();
            tf.fileDownload("D:/testFile/", "下載ftp文件.txt", "C:/Users/17/Desktop/文件", "下載ftp文件.txt", DateTime.Now.ToShortDateString());
        }

      /// <summary>
        /// 下載文件
        /// </summary>
        /// <param name="localPath">本地文件地址(沒有文件名)</param>
        /// <param name="localFileName">本地文件名</param>
        /// <param name="ftpPath">下載的ftp的路徑</param>
        /// <param name="ftpFileName">下載的ftp的文件名</param>
        public bool fileDownload(string localPath, string localFileName, string ftpPath, string ftpFileName, string date)
        {
            bool success = false;
            //FtpWebResponse ftpWebResponse = null;
            FileWebRequest ftpWebRequest = null;
            FileWebResponse ftpWebResponse = null;
            Stream ftpResponseStream = null;
            FileStream outputStream = null;
            try
            {
                //string date = DateTime.Now.ToShortDateString().ToString();//獲取系統時間
                string date1 = date.Replace("/", "");//winods 中文件命名不能有 /   去掉指定字符串 /
                //localPath = localPath + date1 + "/";//拼接路徑

                localPath=Path.Combine(localPath,date1)
                Directory.CreateDirectory(localPath);//建立文件夾名稱
                outputStream = new FileStream(localPath + localFileName, FileMode.Create);//建立文件
                string uri = ftpRootURL + ftpPath + "/" + ftpFileName;//拼接目標文件路徑

                string uri= Path.Combine(ftpRootURL,ftpPath,ftpFileName);
                ftpWebRequest = (FileWebRequest)FileWebRequest.Create(new Uri(uri));              
                //ftpWebRequest1.UseBinary = true;
                ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpWebResponse = (FileWebResponse)ftpWebRequest.GetResponse();
                ftpResponseStream = ftpWebResponse.GetResponseStream();
                long contentLength = ftpWebResponse.ContentLength;
                int bufferSize = 2048;
                byte[] buffer = new byte[bufferSize];
                int readCount;
                readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
                }
                success = true;
            }
            catch (Exception e)
            {

                DirectoryInfo folder = new DirectoryInfo(localPath);
                StreamWriter log = new StreamWriter(localPath + "/" + DateTime.Now.ToShortDateString().ToString().Replace("/", "") + ".txt", true);
                log.WriteLine("發生異常時間:" + System.DateTime.Now.ToShortTimeString().ToString());
                log.WriteLine("發生異常信息:" + e.Message);
                log.WriteLine("發送異常對象:" + e.Source);
                log.WriteLine("調用堆棧:" + e.StackTrace.Trim());
                log.WriteLine("觸動方法:" + e.TargetSite);
                log.WriteLine("   " + e.HResult);
                log.WriteLine("數據對象" + e.Data);
                log.WriteLine("____________________________________________________________");
                log.WriteLine();
                log.Close();
                success = false;
            }
            finally
            {
                if (outputStream != null)
                {
                    outputStream.Close();
                }
                if (ftpResponseStream != null)
                {
                    ftpResponseStream.Close();
                }

                if (ftpWebResponse != null)
                {
                    ftpWebResponse.Close();
                }
            }
            return success;
        }

 

2、 FTP 服務文件下載

這個功能其實和本地文件下載同樣,只須要加幾點便可 

一、FTP服務的地址;

具體代碼以下

       private string ftpIP = "**********";

二、FTP文件服務的登陸帳號以及密碼

具體代碼以下
        private string ftpName = "*********";
        private string ftpPassword = "******";
        private string ftpRootURL = string.Empty;
        FtpWebRequest reqFTP;

三、獲取FTP服務上的文件名稱、FTP文件服務須要下載以後存放的路徑以及下載功能的實現

 FtpWebRequest ftpWebRequest = null;
            FtpWebResponse ftpWebResponse = null;
            Stream ftpResponseStream = null;
            FileStream outputStream = null;
            try
            {
                localFilePath = Path.Combine(localFilePath, ftpFileNameTime);
                Directory.CreateDirectory(localFilePath);//建立文件夾名稱
                outputStream = new FileStream(Path.Combine(localFilePath, fileName), FileMode.Create);
                string uri = Path.Combine(ftpRootURL, ftpIP, fileName);
                ftpWebRequest = (FtpWebRequest)FileWebRequest.Create(new Uri(uri));
                ftpWebRequest.Credentials = new NetworkCredential(ftpName, ftpPassword);//登陸ftp
                ftpWebRequest.UseBinary = true;
                ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
                ftpResponseStream = ftpWebResponse.GetResponseStream();
                long contentLength = ftpWebResponse.ContentLength;
                int bufferSize = 2048;
                byte[] buffer = new byte[bufferSize];
                int readCount;
                readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message)
                /*MessageBox.Show(ex.Message + "是否下載日誌文件", "發送錯誤!", MessageBoxButtons.OKCancel);
                //點擊肯定  就執行下載日誌文件,否則就不執行
                if (dr == DialogResult.OK)
                {
                    WriteLog log = new WriteLog();
                    log.Write_log(ex.Message);
                }*/
            }
            finally
            {
                if (outputStream != null)
                {
                    outputStream.Close();
                }
                if (ftpResponseStream != null)
                {
                    ftpResponseStream.Close();
                }

                if (ftpWebResponse != null)
                {
                    ftpWebResponse.Close();
                }
            }

 

五、具體代碼以下:

namespace FtpDownLoad
{
    public class ftpFileDownload
    {

        private string ftpIP = "*************";
        private string ftpName = "2*******";
        private string ftpPassword = "*********";
        private string ftpRootURL = string.Empty;
        FtpWebRequest reqFTP;

      public static void Main(string[] args)
        {

                 ftpFileDownload ftpDown = new ftpFileDownload();
                 ftpDown.GetFileList("D:\testFile","37.pdt","20190703");

       }

        /// <summary>
        /// 文件下載
        /// </summary>
        /// <param name="localFilePath">下載路徑</param>
        /// <param name="fileName">下載的名稱</param>
        /// <param name="ftpFilePath">FTP路徑</param>
        /// <param name="ftpFileNameTime">FTP文件的修改時間</param>

     public void FtpDownLoadFile(string localFilePath, string fileName, string ftpFileNameTime)
        {
            FtpWebRequest ftpWebRequest = null;
            FtpWebResponse ftpWebResponse = null;
            Stream ftpResponseStream = null;
            FileStream outputStream = null;
            try
            {
                localFilePath = Path.Combine(localFilePath, ftpFileNameTime);
                Directory.CreateDirectory(localFilePath);//建立文件夾名稱
                outputStream = new FileStream(Path.Combine(localFilePath, fileName), FileMode.Create);
                string uri = Path.Combine(ftpRootURL, ftpIP, fileName);
                ftpWebRequest = (FtpWebRequest)FileWebRequest.Create(new Uri(uri));
                ftpWebRequest.Credentials = new NetworkCredential(ftpName, ftpPassword);//登陸ftp
                ftpWebRequest.UseBinary = true;
                ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
                ftpResponseStream = ftpWebResponse.GetResponseStream();
                long contentLength = ftpWebResponse.ContentLength;
                int bufferSize = 2048;
                byte[] buffer = new byte[bufferSize];
                int readCount;
                readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
                }
            }
            catch (Exception ex)
            {

               MessageBox.Show(ex.Message);
              /*  DialogResult dr = MessageBox.Show(ex.Message + "是否下載日誌文件", "發送錯誤!", MessageBoxButtons.OKCancel);
                //點擊肯定  就執行下載日誌文件,否則就不執行
                if (dr == DialogResult.OK)
                {
                    WriteLog log = new WriteLog();
                    log.Write_log(ex.Message);
                }*/
            }
            finally
            {
                if (outputStream != null)
                {
                    outputStream.Close();
                }
                if (ftpResponseStream != null)
                {
                    ftpResponseStream.Close();
                }

                if (ftpWebResponse != null)
                {
                    ftpWebResponse.Close();
                }
            }
        }

若有疑問  能夠往773408602@qq.com發郵件,我會第一時間給你解答的

相關文章
相關標籤/搜索