C# 使用FTP


https://www.cnblogs.com/qiren5761/archive/2010/01/22/1654496.html  感謝大哥

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //FTPUploadFile("127.0.0.1/zwx" , "administrator", "123123", "e:\\飯卡記錄清單.xls");
            //FTPDownloadFile("127.0.0.1/zwx", "administrator", "123123", "d:", "123.xls", "飯卡記錄清單.xls");
            string[] fileList = FTPGetFileList("127.0.0.1/zwx/1", "administrator", "123123");
            for (int i = 0; i < fileList.Length; i++)
            {
                Console.WriteLine(fileList[i]);
            }

            Console.Read();
        }

        #region FTP獲取文件列表

        /// <summary>
        /// FTP獲取文件列表
        /// </summary>
        /// <param name="ftpServerIP"></param>
        /// <param name="ftpUserID"></param>
        /// <param name="ftpPassword"></param>
        /// <returns></returns>
        private static string[] FTPGetFileList(string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            //響應結果
            StringBuilder result = new StringBuilder();

            //FTP請求
            FtpWebRequest ftpRequest = null;

            //FTP響應
            WebResponse ftpResponse = null;

            //FTP響應流
            StreamReader ftpResponsStream = null;

            try
            {
                //生成FTP請求
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));

                //設置文件傳輸類型
                ftpRequest.UseBinary = true;

                //FTP登錄
                ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                //設置FTP方法
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;

                //生成FTP響應
                ftpResponse = ftpRequest.GetResponse();

                //FTP響應流
                ftpResponsStream = new StreamReader(ftpResponse.GetResponseStream());

                string line = ftpResponsStream.ReadLine();

                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = ftpResponsStream.ReadLine();
                }

                //去掉結果列表中最后一個換行
                result.Remove(result.ToString().LastIndexOf('\n'), 1);

                //返回結果
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return (null);
            }
            finally
            {
                if (ftpResponsStream != null)
                {
                    ftpResponsStream.Close();
                }

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

        #endregion

        #region FTP下載文件

        /// <summary>
        /// FTP下載文件
        /// </summary>
        /// <param name="ftpServerIP">FTP服務器IP</param>
        /// <param name="ftpUserID">FTP登錄帳號</param>
        /// <param name="ftpPassword">FTP登錄密碼</param>
        /// <param name="saveFilePath">保存文件路徑</param>
        /// <param name="saveFileName">保存文件名</param>
        /// <param name="downloadFileName">下載文件名</param>
        private static void FTPDownloadFile(string ftpServerIP, string ftpUserID, string ftpPassword,
            string saveFilePath, string saveFileName, string downloadFileName)
        {
            //定義FTP請求對象
            FtpWebRequest ftpRequest = null;
            //定義FTP響應對象
            FtpWebResponse ftpResponse = null;

            //存儲流
            FileStream saveStream = null;
            //FTP數據流
            Stream ftpStream = null;

            try
            {
                //生成下載文件
                saveStream = new FileStream(saveFilePath + "\\" + saveFileName, FileMode.Create);

                //生成FTP請求對象
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + downloadFileName));

                //設置下載文件方法
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

                //設置文件傳輸類型
                ftpRequest.UseBinary = true;

                //設置登錄FTP帳號和密碼
                ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                //生成FTP響應對象
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                //獲取FTP響應流對象
                ftpStream = ftpResponse.GetResponseStream();

                //響應數據長度
                long cl = ftpResponse.ContentLength;

                int bufferSize = 2048;

                int readCount;

                byte[] buffer = new byte[bufferSize];

                //接收FTP文件流
                readCount = ftpStream.Read(buffer, 0, bufferSize);

                while (readCount > 0)
                {
                    saveStream.Write(buffer, 0, readCount);

                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (ftpStream != null)
                {
                    ftpStream.Close();
                }
               
                if (saveStream != null)
                {
                    saveStream.Close();
                }

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

        #endregion

        #region FTP上傳文件

        /// <summary>
        /// FTP上傳文件
        /// </summary>
        /// <param name="ftpServerIP">FTP服務器IP</param>
        /// <param name="ftpUserID">FTP登錄帳號</param>
        /// <param name="ftpPassword">FTP登錄密碼</param>
        /// <param name="filename">上文件文件名(絕對路徑)</param>
        private static void FTPUploadFile(string ftpServerIP, string ftpUserID, string ftpPassword, string filename)
        {
            //上傳文件
            FileInfo uploadFile = null;
           
            //上傳文件流
            FileStream uploadFileStream = null;

            //FTP請求對象
            FtpWebRequest ftpRequest = null;

            //FTP流
            Stream ftpStream = null;

            try
            {
                //獲取上傳文件
                uploadFile = new FileInfo(filename);

                //創建FtpWebRequest對象
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + uploadFile.Name));

                //FTP登錄
                ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                // 默認為true,連接不會被關閉
                // 在一個命令之后被執行
                ftpRequest.KeepAlive = false;

                //FTP請求執行方法
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

                // 指定數據傳輸類型
                ftpRequest.UseBinary = true;

                // 上傳文件時通知服務器文件的大小
                ftpRequest.ContentLength = uploadFile.Length;

                // 緩沖大小設置為2kb
                int buffLength = 2048;

                byte[] buff = new byte[buffLength];
                int contentLen;

                // 打開一個文件流讀上傳的文件
                uploadFileStream = uploadFile.OpenRead();

                // 把上傳的文件寫入流
                ftpStream = ftpRequest.GetRequestStream();

                // 每次讀文件流的2kb
                contentLen = uploadFileStream.Read(buff, 0, buffLength);

                // 流內容沒有結束
                while (contentLen != 0)
                {
                    // 把內容從file stream 寫入 upload stream
                    ftpStream.Write(buff, 0, contentLen);

                    contentLen = uploadFileStream.Read(buff, 0, buffLength);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (uploadFileStream != null)
                {
                    uploadFileStream.Close();
                }

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

        #endregion
    }
}

 
分類:  .NE


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM