C# FTP下载一目录下所有文件夹及文件

时间:2022-12-06 12:33:05

C# FTP下载一目录下所有文件夹及文件

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Net;  
using System.IO;  
 
namespace FtpDownload  
{  
 
    class FtpDownloadUtil  
    {  
        private const string LogFileName = "FtpLog.txt";  
 
        private string userName;  
        private string password;  
 
        public FtpDownloadUtil()  
        {  
            userName = "Anonymous";  
            password = "";  
        }  
 
        public FtpDownloadUtil(string uName, string pwd)  
        {  
            if (string.IsNullOrEmpty(uName) || string.IsNullOrEmpty(pwd))  
            {  
                userName = "Anonymous";  
                password = "";  
            }  
            else 
            {  
                userName = uName;  
                password = pwd;  
            }  
        }  
 
        private void recordLog(string exM)  
        {  
            File.AppendAllText(LogFileName, DateTime.Now.ToString() + "-------------------------------" + Environment.NewLine);  
            File.AppendAllText(LogFileName, exM);  
        }  
 
        public FtpWebRequest CreateFtpConnect(string ftpAdd)  
        {  
            try 
            {  
                FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpAdd));  
                ftpRequest.Credentials = new NetworkCredential(userName, password);  
                ftpRequest.UseBinary = true;  
                return ftpRequest;  
            }  
            catch (Exception ex)  
            {  
                recordLog(ex.Message);  
                return null;  
            }  
        }  
 
        private string[] GetFtpFileList(string ftpAdd, string wRMetod)  
        {  
            FtpWebRequest ftpRequest = CreateFtpConnect(ftpAdd);  
            if (ftpRequest != null)  
            {  
                StringBuilder fileListBuilder = new StringBuilder();  
                ftpRequest.Method = wRMetod;  
                try 
                {  
                    WebResponse ftpResponse = ftpRequest.GetResponse();  
                    StreamReader ftpFileListReader = new StreamReader(ftpResponse.GetResponseStream(), Encoding.Default);  
 
                    string line = ftpFileListReader.ReadLine();  
                    while (line != null)  
                    {  
                        fileListBuilder.Append(line);  
                        fileListBuilder.Append("/n");  
                        line = ftpFileListReader.ReadLine();  
                    }  
                    ftpFileListReader.Close();  
                    ftpResponse.Close();  
                    fileListBuilder.Remove(fileListBuilder.ToString().LastIndexOf('/n'), 1);  
                    return fileListBuilder.ToString().Split('/n');  
                }  
                catch (Exception ex)  
                {  
                    recordLog(ex.Message);  
                    return null;  
                }  
            }  
            else 
            {  
                return null;  
            }  
        }  
 
        /// <summary>  
        /// 类似于 ftp://127.0.0.1/  
        /// 实现下载一个指定FTP目录下所有的文件和文件夹  
        /// </summary>  
        /// <param name="ftpAdd"></param>  
        /// <param name="localDir"></param>  
        /// <returns></returns>  
       public bool DownloadDirectory(string ftpAddress, string dirName, string localDir)  
        {  
 
            String[] fileList = null;  
            string downloadDir = string.Empty;  
            if (dirName != string.Empty)  
            {  
                fileList = GetFileList(ftpAddress + dirName + "/", WebRequestMethods.Ftp.ListDirectoryDetails);  
                downloadDir = localDir + "//" + dirName;  
                if (!Directory.Exists(downloadDir))  
                {  
                    Directory.CreateDirectory(downloadDir);  
                }  
            }  
            else 
            {  
                return false;  
            }  
 
            List<string> directory = new List<string>();  
            string[] temp = null;  
            string[] files = GetFileList(ftpAddress + dirName + "/", WebRequestMethods.Ftp.ListDirectory);  
 
            if (fileList != null)  
            {  
                foreach (string file in fileList)  
                {  
                    if (file.Contains("<DIR>")) //if this is a dir need recursion download  
                    {  
                        temp = file.Trim().Split(new string[] { "<DIR>" }, StringSplitOptions.None);  
                        directory.Add(temp[1].Trim());  
                        temp = null;  
                    }  
                }  
            }  
            else   
            {  
                return false;  
            }  
 
            if (directory.Count > 0 && directory.Count < fileList.Length)  
            {  
                foreach (string fi in files)  
                {  
                    if (!directory.Contains(fi.Trim()))  
                    {  
                        this.DownloadFile(ftpAddress + dirName + "/" + fi.Trim(), fi.Trim(), downloadDir);  
                    }  
                }  
            }  
            else if (directory.Count == 0 && fileList.Length > 0)  
            {  
                foreach (string fi in files)  
                {  
                    this.DownloadFile(ftpAddress + dirName + "/" + fi.Trim(), fi.Trim(), downloadDir);  
                }  
            }  
 
            if (directory.Count > 0)  
            {  
                foreach (string dir in directory)  
                {  
 
                    DownloadDirectory(ftpAddress + dirName + "/", dir, downloadDir);  
                }  
            }  
            return true;  
        }  
 
        public bool DownloadFileFromFtp(string FtpAdd, string fileName,string localDir)  
        {  
            return true;  
        }  
    }  

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

namespace FtpDownload
{

    class FtpDownloadUtil
    {
        private const string LogFileName = "FtpLog.txt";

        private string userName;
        private string password;

        public FtpDownloadUtil()
        {
            userName = "Anonymous";
            password = "";
        }

        public FtpDownloadUtil(string uName, string pwd)
        {
            if (string.IsNullOrEmpty(uName) || string.IsNullOrEmpty(pwd))
            {
                userName = "Anonymous";
                password = "";
            }
            else
            {
                userName = uName;
                password = pwd;
            }
        }

        private void recordLog(string exM)
        {
            File.AppendAllText(LogFileName, DateTime.Now.ToString() + "-------------------------------" + Environment.NewLine);
            File.AppendAllText(LogFileName, exM);
        }

        public FtpWebRequest CreateFtpConnect(string ftpAdd)
        {
            try
            {
                FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpAdd));
                ftpRequest.Credentials = new NetworkCredential(userName, password);
                ftpRequest.UseBinary = true;
                return ftpRequest;
            }
            catch (Exception ex)
            {
                recordLog(ex.Message);
                return null;
            }
        }

        private string[] GetFtpFileList(string ftpAdd, string wRMetod)
        {
            FtpWebRequest ftpRequest = CreateFtpConnect(ftpAdd);
            if (ftpRequest != null)
            {
                StringBuilder fileListBuilder = new StringBuilder();
                ftpRequest.Method = wRMetod;
                try
                {
                    WebResponse ftpResponse = ftpRequest.GetResponse();
                    StreamReader ftpFileListReader = new StreamReader(ftpResponse.GetResponseStream(), Encoding.Default);

                    string line = ftpFileListReader.ReadLine();
                    while (line != null)
                    {
                        fileListBuilder.Append(line);
                        fileListBuilder.Append("/n");
                        line = ftpFileListReader.ReadLine();
                    }
                    ftpFileListReader.Close();
                    ftpResponse.Close();
                    fileListBuilder.Remove(fileListBuilder.ToString().LastIndexOf('/n'), 1);
                    return fileListBuilder.ToString().Split('/n');
                }
                catch (Exception ex)
                {
                    recordLog(ex.Message);
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 类似于 ftp://127.0.0.1/
        /// 实现下载一个指定FTP目录下所有的文件和文件夹
        /// </summary>
        /// <param name="ftpAdd"></param>
        /// <param name="localDir"></param>
        /// <returns></returns>
       public bool DownloadDirectory(string ftpAddress, string dirName, string localDir)
        {

            String[] fileList = null;
            string downloadDir = string.Empty;
            if (dirName != string.Empty)
            {
                fileList = GetFileList(ftpAddress + dirName + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
                downloadDir = localDir + "//" + dirName;
                if (!Directory.Exists(downloadDir))
                {
                    Directory.CreateDirectory(downloadDir);
                }
            }
            else
            {
                return false;
            }

            List<string> directory = new List<string>();
            string[] temp = null;
            string[] files = GetFileList(ftpAddress + dirName + "/", WebRequestMethods.Ftp.ListDirectory);

            if (fileList != null)
            {
                foreach (string file in fileList)
                {
                    if (file.Contains("<DIR>")) //if this is a dir need recursion download
                    {
                        temp = file.Trim().Split(new string[] { "<DIR>" }, StringSplitOptions.None);
                        directory.Add(temp[1].Trim());
                        temp = null;
                    }
                }
            }
            else
            {
                return false;
            }

            if (directory.Count > 0 && directory.Count < fileList.Length)
            {
                foreach (string fi in files)
                {
                    if (!directory.Contains(fi.Trim()))
                    {
                        this.DownloadFile(ftpAddress + dirName + "/" + fi.Trim(), fi.Trim(), downloadDir);
                    }
                }
            }
            else if (directory.Count == 0 && fileList.Length > 0)
            {
                foreach (string fi in files)
                {
                    this.DownloadFile(ftpAddress + dirName + "/" + fi.Trim(), fi.Trim(), downloadDir);
                }
            }

            if (directory.Count > 0)
            {
                foreach (string dir in directory)
                {

                    DownloadDirectory(ftpAddress + dirName + "/", dir, downloadDir);
                }
            }
            return true;
        }

        public bool DownloadFileFromFtp(string FtpAdd, string fileName,string localDir)
        {
            return true;
        }
    }
}
 

主要实现了FTP目录下所有文件夹及文件的下载,有些函数没写完,后续补充完整!


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/tianhongmu/archive/2010/01/18/5209510.aspx