【轉載】C#如何操控FTP,獲取FTP文件或文件夾列表,獲取FTP文件大小,FTP上傳,FTP刪除文件,FTP新建文件夾、刪除文件夾

C#如何操控FTP

出處:http://www.cnblogs.com/rond/archive/2012/07/30/2611295.htmlhttp://www.cnblogs.com/rondhtml

 

關於FTP的應用免不了要對FTP進行增刪查改什麼的。經過搜索,整理和修改,本身寫了一個FTP的Helper類。此篇文章目的有二(2最近流行)。服務器

    • 累積代碼,方便本身之後查閱使用;
    • 分享代碼,方便他人使用。

如下是類:

FtpHelper.cs

 如下是重點說明:

如何獲取某一目錄下的文件和文件夾列表。post

因爲FtpWebRequest類只提供了WebRequestMethods.Ftp.ListDirectory方式和WebRequestMethods.Ftp.ListDirectoryDetails方式。這個方法獲取到的是包含文件列表和文件夾列表的信息。並非單單隻包含某一類。爲此咱們須要分析獲取信息的特色。分析發現,對於文件夾會有「<DIR>」這一項,而文件沒有。因此咱們能夠根據這個來區分。一下分別是獲取文件列表和文件夾列表的代碼:ui

獲取文件夾:url

複製代碼
/// <summary>
/// 從ftp服務器上得到文件夾列表
/// </summary>
/// <param name="RequedstPath">服務器下的相對路徑</param>
/// <returns></returns>
public static List<string> GetDirctory(string RequedstPath)
{
    List<string> strs = new List<string>();
    try
    {
        string uri = path + RequedstPath;   //目標路徑 path爲服務器地址
        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
        // ftp用戶名和密碼
        reqFTP.Credentials = new NetworkCredential(username, password);
        reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
        WebResponse response = reqFTP.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

        string line = reader.ReadLine();
        while (line != null)
        {
            if (line.Contains("<DIR>"))
            {
                string msg = line.Substring(line.LastIndexOf("<DIR>")+5).Trim();
                strs.Add(msg);
            }
            line = reader.ReadLine();
        }
        reader.Close();
        response.Close();
        return strs;
    }
    catch (Exception ex)
    {
        Console.WriteLine("獲取目錄出錯:" + ex.Message);
    }
    return strs;
}
複製代碼

獲取文件列表spa

複製代碼
/// <summary>
/// 從ftp服務器上得到文件列表
/// </summary>
/// <param name="RequedstPath">服務器下的相對路徑</param>
/// <returns></returns>
public static List<string> GetFile(string RequedstPath)
{
    List<string> strs = new List<string>();
    try
    {
        string uri = path + RequedstPath;   //目標路徑 path爲服務器地址
        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
        // ftp用戶名和密碼
        reqFTP.Credentials = new NetworkCredential(username, password);
        reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
        WebResponse response = reqFTP.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

        string line = reader.ReadLine();
        while (line != null)
        {
            if (!line.Contains("<DIR>"))
            {
                string msg = line.Substring(39).Trim();
                strs.Add(msg);
            }
            line = reader.ReadLine();
        }
        reader.Close();
        response.Close();
        return strs;
    }
    catch (Exception ex)
    {
        Console.WriteLine("獲取文件出錯:" + ex.Message);
    }
    return strs;
}
複製代碼

其餘代碼並不須要過多的說明,註釋已經說的至關明確了。code

複製代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;

namespace FtpSyn
{
    static public class FtpHelper
    {
        //基本設置
        static private string path = @"ftp://" + Helper.GetAppConfig("obj") + "/";    //目標路徑
        static private string ftpip =Helper.GetAppConfig("obj");    //ftp IP地址
        static private string username = Helper.GetAppConfig("username");   //ftp用戶名
        static private string password = Helper.GetAppConfig("password");   //ftp密碼

        //獲取ftp上面的文件和文件夾
        public static string[] GetFileList(string dir)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest request;
            try
            {
                request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
                request.UseBinary = true;
                request.Credentials = new NetworkCredential(username, password);//設置用戶名和密碼
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.UseBinary = true;

                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    Console.WriteLine(line);
                    line = reader.ReadLine();
                }
                // to remove the trailing '\n'
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                Console.WriteLine("獲取ftp上面的文件和文件夾:" + ex.Message);
                downloadFiles = null;
                return downloadFiles;
            }
        }

        /// <summary>
        /// 獲取文件大小
        /// </summary>
        /// <param name="file">ip服務器下的相對路徑</param>
        /// <returns>文件大小</returns>
        public static int GetFileSize(string file)
        {
            StringBuilder result = new StringBuilder();
            FtpWebRequest request;
            try
            {
                request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + file));
                request.UseBinary = true;
                request.Credentials = new NetworkCredential(username, password);//設置用戶名和密碼
                request.Method = WebRequestMethods.Ftp.GetFileSize;

                int dataLength = (int)request.GetResponse().ContentLength;

                return dataLength;
            }
            catch (Exception ex)
            {
                Console.WriteLine("獲取文件大小出錯:" + ex.Message);
                return -1;
            }
        }

        /// <summary>
        /// 文件上傳
        /// </summary>
        /// <param name="filePath">原路徑(絕對路徑)包括文件名</param>
        /// <param name="objPath">目標文件夾:服務器下的相對路徑 不填爲根目錄</param>
        public static void FileUpLoad(string filePath,string objPath="")
        {
            try
            {
                string url = path;
                if(objPath!="")
                    url += objPath + "/";
                try
                {

                    FtpWebRequest reqFTP = null;
                    //待上傳的文件 (全路徑)
                    try
                    {
                        FileInfo fileInfo = new FileInfo(filePath);
                        using (FileStream fs = fileInfo.OpenRead())
                        {
                            long length = fs.Length;
                            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + fileInfo.Name));

                            //設置鏈接到FTP的賬號密碼
                            reqFTP.Credentials = new NetworkCredential(username, password);
                            //設置請求完成後是否保持鏈接
                            reqFTP.KeepAlive = false;
                            //指定執行命令
                            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                            //指定數據傳輸類型
                            reqFTP.UseBinary = true;

                            using (Stream stream = reqFTP.GetRequestStream())
                            {
                                //設置緩衝大小
                                int BufferLength = 5120;
                                byte[] b = new byte[BufferLength];
                                int i;
                                while ((i = fs.Read(b, 0, BufferLength)) > 0)
                                {
                                    stream.Write(b, 0, i);
                                }
                                Console.WriteLine("上傳文件成功");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("上傳文件失敗錯誤爲" + ex.Message);
                    }
                    finally
                    {

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("上傳文件失敗錯誤爲" + ex.Message);
                }
                finally
                {

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("上傳文件失敗錯誤爲" + ex.Message);
            }
        }
        
        /// <summary>
        /// 刪除文件
        /// </summary>
        /// <param name="fileName">服務器下的相對路徑 包括文件名</param>
        public static void DeleteFileName(string fileName)
        {
            try
            {
                FileInfo fileInf = new FileInfo(ftpip +""+ fileName);
                string uri = path + fileName;
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // 指定數據傳輸類型
                reqFTP.UseBinary = true;
                // ftp用戶名和密碼
                reqFTP.Credentials = new NetworkCredential(username, password);
                // 默認爲true,鏈接不會被關閉
                // 在一個命令以後被執行
                reqFTP.KeepAlive = false;
                // 指定執行什麼命令
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("刪除文件出錯:" + ex.Message);
            }
        }
        
        /// <summary>
        /// 新建目錄 上一級必須先存在
        /// </summary>
        /// <param name="dirName">服務器下的相對路徑</param>
        public static void MakeDir(string dirName)
        {
            try
            {
                string uri = path + dirName;
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // 指定數據傳輸類型
                reqFTP.UseBinary = true;
                // ftp用戶名和密碼
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("建立目錄出錯:" + ex.Message);
            }
        }
        
        /// <summary>
        /// 刪除目錄 上一級必須先存在
        /// </summary>
        /// <param name="dirName">服務器下的相對路徑</param>
        public static void DelDir(string dirName)
        {
            try
            {
                string uri = path + dirName;
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用戶名和密碼
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("刪除目錄出錯:" + ex.Message);
            }
        }

        /// <summary>
        /// 從ftp服務器上得到文件夾列表
        /// </summary>
        /// <param name="RequedstPath">服務器下的相對路徑</param>
        /// <returns></returns>
        public static List<string> GetDirctory(string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = path + RequedstPath;   //目標路徑 path爲服務器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用戶名和密碼
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

                string line = reader.ReadLine();
                while (line != null)
                {
                    if (line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(line.LastIndexOf("<DIR>")+5).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("獲取目錄出錯:" + ex.Message);
            }
            return strs;
        }

        /// <summary>
        /// 從ftp服務器上得到文件列表
        /// </summary>
        /// <param name="RequedstPath">服務器下的相對路徑</param>
        /// <returns></returns>
        public static List<string> GetFile(string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = path + RequedstPath;   //目標路徑 path爲服務器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用戶名和密碼
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

                string line = reader.ReadLine();
                while (line != null)
                {
                    if (!line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(39).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("獲取文件出錯:" + ex.Message);
            }
            return strs;
        }
    
    }
}
複製代碼
相關文章
相關標籤/搜索