LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

【C#】FTPHelper-封装FTP的相关操作

admin
2021年5月11日 17:32 本文热度 2556

using System;

using System.IO;

using System.Net;

using System.Text;

 

namespace Whir.Software.DataSyncTools.Library.Helper

{

    /// <summary>

    ///     Ftp辅助类

    /// </summary>

    public class FtpHelper

    {

        private const int BufferSize = 2048;

        private readonly string _host;

        private readonly string _pass;

        private readonly string _user;

        private FtpWebRequest _ftpRequest;

        private FtpWebResponse _ftpResponse;

        private Stream _ftpStream;

 

        public FtpHelper(string hostIp, string userName, string password)

        {

            _host = hostIp;

            _user = userName;

            _pass = password;

        }

 

        /// <summary>

        ///     下载文件

        /// </summary>

        /// <param name="localFile"></param>

        /// <param name="remoteFile"></param>

        /// <returns></returns>

        public FtpResult Download(string localFile, string remoteFile)

        {

            FtpResult result;

            try

            {

                _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + remoteFile);

                _ftpRequest.Credentials = new NetworkCredential(_user, _pass);

                _ftpRequest.UseBinary = true;

                _ftpRequest.UsePassive = true;

                _ftpRequest.KeepAlive = true;

                _ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

                _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();

                _ftpStream = _ftpResponse.GetResponseStream();

                var localFileStream = new FileStream(localFile, FileMode.Create);

                var byteBuffer = new byte[BufferSize];

                if (_ftpStream != null)

                {

                    int bytesRead = _ftpStream.Read(byteBuffer, 0, BufferSize);

                    try

                    {

                        while (bytesRead > 0)

                        {

                            localFileStream.Write(byteBuffer, 0, bytesRead);

                            bytesRead = _ftpStream.Read(byteBuffer, 0, BufferSize);

                        }

                    }

                    catch (Exception ex)

                    {

                        result = new FtpResult(false, ex.Message);

                        return result;

                    }

                }

                localFileStream.Close();

                if (_ftpStream != null) _ftpStream.Close();

                _ftpResponse.Close();

                _ftpRequest = null;

                result = new FtpResult(true, "ok");

            }

            catch (Exception ex)

            {

                result = new FtpResult(false, ex.Message);

            }

            return result;

        }

 

        /// <summary>

        ///     上传文件

        /// </summary>

        /// <param name="localFile"></param>

        /// <param name="remoteFile"></param>

        /// <returns></returns>

        public FtpResult Upload(string localFile, string remoteFile)

        {

            FtpResult result;

            try

            {

                _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + remoteFile);

                _ftpRequest.Credentials = new NetworkCredential(_user, _pass);

                _ftpRequest.UseBinary = true;

                _ftpRequest.UsePassive = true;

                _ftpRequest.KeepAlive = true;

                _ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

                _ftpStream = _ftpRequest.GetRequestStream();

                var localFileStream = new FileStream(localFile, FileMode.Create);

                var byteBuffer = new byte[BufferSize];

                int bytesSent = localFileStream.Read(byteBuffer, 0, BufferSize);

                try

                {

                    while (bytesSent != 0)

                    {

                        _ftpStream.Write(byteBuffer, 0, bytesSent);

                        bytesSent = localFileStream.Read(byteBuffer, 0, BufferSize);

                    }

                }

                catch (Exception ex)

                {

                    result = new FtpResult(false, ex.Message);

                    return result;

                }

                localFileStream.Close();

                _ftpStream.Close();

                _ftpRequest = null;

                result = new FtpResult(true, "ok");

            }

            catch (Exception ex)

            {

                result = new FtpResult(false, ex.Message);

            }

            return result;

        }

 

        /// <summary>

        ///     删除文件

        /// </summary>

        /// <param name="deleteFile"></param>

        public FtpResult Delete(string deleteFile)

        {

            FtpResult result;

            try

            {

                _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + deleteFile);

                _ftpRequest.Credentials = new NetworkCredential(_user, _pass);

                _ftpRequest.UseBinary = true;

                _ftpRequest.UsePassive = true;

                _ftpRequest.KeepAlive = true;

                _ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;

                _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();

                _ftpResponse.Close();

                _ftpRequest = null;

                result = new FtpResult(true, "ok");

            }

            catch (Exception ex)

            {

                result = new FtpResult(false, ex.Message);

            }

            return result;

        }

 

        /// <summary>

        ///     文件重命名

        /// </summary>

        /// <param name="currentFileNameAndPath"></param>

        /// <param name="newFileName"></param>

        /// <returns></returns>

        public FtpResult Rename(string currentFileNameAndPath, string newFileName)

        {

            FtpResult result;

            try

            {

                _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + currentFileNameAndPath);

                _ftpRequest.Credentials = new NetworkCredential(_user, _pass);

                _ftpRequest.UseBinary = true;

                _ftpRequest.UsePassive = true;

                _ftpRequest.KeepAlive = true;

                _ftpRequest.Method = WebRequestMethods.Ftp.Rename;

                _ftpRequest.RenameTo = newFileName;

                _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();

                _ftpResponse.Close();

                _ftpRequest = null;

                result = new FtpResult(true, "ok");

            }

            catch (Exception ex)

            {

                result = new FtpResult(false, ex.Message);

            }

            return result;

        }

 

        /// <summary>

        ///     创建目录

        /// </summary>

        /// <param name="newDirectory"></param>

        /// <returns></returns>

        public FtpResult CreateDirectory(string newDirectory)

        {

            FtpResult result;

            try

            {

                _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + newDirectory);

                _ftpRequest.Credentials = new NetworkCredential(_user, _pass);

                _ftpRequest.UseBinary = true;

                _ftpRequest.UsePassive = true;

                _ftpRequest.KeepAlive = true;

                _ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;

                _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();

                _ftpResponse.Close();

                _ftpRequest = null;

                result = new FtpResult(true, "ok");

            }

            catch (Exception ex)

            {

                result = new FtpResult(false, ex.Message);

            }

            return result;

        }

 

        /// <summary>

        ///     取得文件创建时间

        /// </summary>

        /// <param name="fileName"></param>

        /// <returns></returns>

        public FtpResult GetFileCreatedDateTime(string fileName)

        {

            FtpResult result;

            try

            {

                _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + fileName);

                _ftpRequest.Credentials = new NetworkCredential(_user, _pass);

                _ftpRequest.UseBinary = true;

                _ftpRequest.UsePassive = true;

                _ftpRequest.KeepAlive = true;

                _ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;

                _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();

                _ftpStream = _ftpResponse.GetResponseStream();

                if (_ftpStream != null)

                {

                    var ftpReader = new StreamReader(_ftpStream);

                    string fileInfo;

                    try

                    {

                        fileInfo = ftpReader.ReadToEnd();

                    }

                    catch (Exception ex)

                    {

                        result = new FtpResult(false, ex.Message);

                        ftpReader.Close();

                        if (_ftpStream != null) _ftpStream.Close();

                        _ftpResponse.Close();

                        _ftpRequest = null;

                        return result;

                    }

                    ftpReader.Close();

                    if (_ftpStream != null) _ftpStream.Close();

                    _ftpResponse.Close();

                    _ftpRequest = null;

                    return new FtpResult(true, fileInfo);

                }

                return new FtpResult(false, "响应流为空");

            }

            catch (Exception ex)

            {

                result = new FtpResult(false, ex.Message);

            }

            return result;

        }

 

        /// <summary>

        ///     取得文件大小

        /// </summary>

        /// <param name="fileName"></param>

        /// <returns></returns>

        public FtpResult GetFileSize(string fileName)

        {

            FtpResult result;

            try

            {

                _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + fileName);

                _ftpRequest.Credentials = new NetworkCredential(_user, _pass);

                _ftpRequest.UseBinary = true;

                _ftpRequest.UsePassive = true;

                _ftpRequest.KeepAlive = true;

                _ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;

                _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();

                _ftpStream = _ftpResponse.GetResponseStream();

                if (_ftpStream != null)

                {

                    var ftpReader = new StreamReader(_ftpStream);

                    string fileInfo = null;

                    try

                    {

                        while (ftpReader.Peek() != -1)

                        {

                            fileInfo = ftpReader.ReadToEnd();

                        }

                    }

                    catch (Exception ex)

                    {

                        result = new FtpResult(false, ex.Message);

                        ftpReader.Close();

                        if (_ftpStream != null) _ftpStream.Close();

                        _ftpResponse.Close();

                        _ftpRequest = null;

                        return result;

                    }

                    ftpReader.Close();

                    _ftpStream.Close();

                    _ftpResponse.Close();

                    _ftpRequest = null;

                    return new FtpResult(true, fileInfo);

                }

                result = new FtpResult(false, "响应流为空");

            }

            catch (Exception ex)

            {

                result = new FtpResult(false, ex.Message);

            }

            return result;

        }

 

        /// <summary>

        ///     显示远程目录结构

        /// </summary>

        /// <param name="directory"></param>

        /// <returns></returns>

        public string[] DirectoryListSimple(string directory)

        {

            try

            {

                _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + directory);

                _ftpRequest.Credentials = new NetworkCredential(_user, _pass);

                _ftpRequest.UseBinary = true;

                _ftpRequest.UsePassive = true;

                _ftpRequest.KeepAlive = true;

                _ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;

                _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();

                _ftpStream = _ftpResponse.GetResponseStream();

                if (_ftpStream != null)

                {

                    var ftpReader = new StreamReader(_ftpStream);

                    string directoryRaw = null;

                    try

                    {

                        while (ftpReader.Peek() != -1)

                        {

                            directoryRaw += ftpReader.ReadLine() + "|";

                        }

                    }

                    catch (Exception ex)

                    {

                        Console.WriteLine(ex.ToString());

                    }

                    ftpReader.Close();

                    _ftpStream.Close();

                    _ftpResponse.Close();

                    _ftpRequest = null;

                    /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */

                    try

                    {

                        if (directoryRaw != null)

                        {

                            string[] directoryList = directoryRaw.Split("|".ToCharArray());

                            return directoryList;

                        }

                    }

                    catch (Exception ex)

                    {

                        Console.WriteLine(ex.ToString());

                    }

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.ToString());

            }

            return new[] { "" };

        }

 

        /// <summary>

        ///     远程文件列表

        /// </summary>

        /// <param name="directory"></param>

        /// <returns></returns>

        public string[] DirectoryListDetailed(string directory)

        {

            try

            {

                _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + directory);

                _ftpRequest.Credentials = new NetworkCredential(_user, _pass);

                _ftpRequest.UseBinary = true;

                _ftpRequest.UsePassive = true;

                _ftpRequest.KeepAlive = true;

                _ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

                _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();

                _ftpStream = _ftpResponse.GetResponseStream();

                if (_ftpStream != null)

                {

                    var ftpReader = new StreamReader(_ftpStream);

                    string directoryRaw = null;

                    try

                    {

                        while (ftpReader.Peek() != -1)

                        {

                            directoryRaw += ftpReader.ReadLine() + "|";

                        }

                    }

                    catch (Exception ex)

                    {

                        Console.WriteLine(ex.ToString());

                    }

                    ftpReader.Close();

                    _ftpStream.Close();

                    _ftpResponse.Close();

                    _ftpRequest = null;

                    try

                    {

                        if (directoryRaw != null)

                        {

                            string[] directoryList = directoryRaw.Split("|".ToCharArray());

                            return directoryList;

                        }

                    }

                    catch (Exception ex)

                    {

                        Console.WriteLine(ex.ToString());

                    }

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.ToString());

            }

            /* Return an Empty string Array if an Exception Occurs */

            return new[] { "" };

        }

    }

 

    public class FtpResult

    {

        public FtpResult(bool isCusecess, string message)

        {

            IsSucess = isCusecess;

            Message = message;

        }

 

        public bool IsSucess { get; set; }

        public string Message { get; set; }

    }

}


该文章在 2021/5/11 17:33:25 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved