`
380071587
  • 浏览: 493443 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

FTPHelper-封装FTP的相关操作

 
阅读更多
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; }
    }
}


分享到:
评论

相关推荐

    C# FTP操作帮助类, FTPHelper.cs

    C# FTP操作帮助类, FTPHelper.cs,已经封装好了FTP相关的各个操作的方法

    Apache Common-net Ftp客户端实例

    接下来,我们将创建一个名为`FtpHelper`的Java类,用于封装FTP操作。`FtpHelper.java`文件的内容可能如下: ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import...

    C# FTP操作最全类 WPF实现

    "FTPHelper"是一个实用的C#类,它封装了FTP相关的操作,如连接、登录、文件和目录管理等。这个类通常包含静态方法,便于在应用程序的任何地方调用。例如,它可能有如下方法: - `Connect(string host, string ...

    FTP操作帮助类

    为了封装这些操作,你可以创建一个FTP帮助类,提供如Connect、Upload、Download、Delete等静态方法,以便在项目中轻松调用。例如: ```csharp public static class FtpHelper { public static void Connect(string...

    C# FtpHelper 上传

    在提供的压缩包文件中,`Ftp`可能是包含这个FtpHelper类或其他相关FTP操作代码的文件或文件夹。为了深入了解这个工具的实现,你可以查看这个文件中的源代码,学习作者是如何组织和实现FTP上传功能的。这有助于提升你...

    FTPHelper 帮助类

    总之,FTPHelper 类是C++环境中实现FTP功能的一个实用工具,通过提供简单的API,使得开发者可以方便地进行文件的上传、下载和其他FTP相关的操作。在实际项目中,它简化了FTP交互的复杂性,提高了代码的可读性和可...

    C#操作FTP公用类,FTP上传下载公用类

    通过上述介绍可以看出,`FtpHelper`类为处理FTP相关任务提供了一个坚实的基础。开发者可以根据具体需求进一步扩展该类的功能,如增加文件上传、下载、删除等功能,以及优化异常处理机制,提高程序的健壮性和用户体验...

    C#基类库大全下载--苏飞版

    FTPHelper-FTP帮助类,FTP常用操作方法,添加文件,删除文件等 FTPOperater FTP操作帮助类,方法比较多,比较实用 6.JS操作类 JsHelper JsHelper--Javascript操作帮助类,输出各种JS方法,方便不懂JS的人使用,...

    C# FTP操作辅助类

    为了封装这些功能,我们可以创建一个名为`FtpHelper`的辅助类。类中可以包含以下方法: 1. **Connect**:初始化FtpWebRequest对象,建立与FTP服务器的连接。 2. **UploadFile**:接收文件路径和FTP路径,将本地文件...

    c#类库工具封装

    你可以创建一个FtpHelper类,封装FTP的登录、上传、下载、删除文件等操作。例如: ```csharp public class FtpHelper { public void UploadFile(string serverPath, string localPath) { // 实现FTP上传代码 } ...

    C#基础类库

    FTPHelper-FTP帮助类,FTP常用操作方法,添加文件,删除文件等 FTPOperater FTP操作帮助类,方法比较多,比较实用 6.JS操作类 JsHelper JsHelper--Javascript操作帮助类,输出各种JS方法,方便不懂JS的人使用,...

    C#开发教程之ftp操作方法整理

    总结来说,C#开发中进行FTP操作时,可以利用FtpWebRequest类提供的基础功能,但为了方便和扩展,通常会创建自定义辅助类,如FtpHelper,来封装复杂的操作。通过这样的封装,我们可以更高效地进行文件上传、下载以及...

    c# 上传下载FTP文件

    为了实现这些功能,我们可以封装一个FTP操作的类,如`FtpHelper`,它包含如`UploadFile`、`DownloadFile`、`ListDirectory`等方法,方便在项目中复用。实例演示中提供的`UpFtp`文件可能包含了这样的类和示例代码。 ...

    C#基类库(苏飞版)

    FTPHelper-FTP帮助类,FTP常用操作方法,添加文件,删除文件等 FTPOperater FTP操作帮助类,方法比较多,比较实用 6.JS操作类 JsHelper JsHelper--Javascript操作帮助类,输出各种JS方法,方便不懂JS的人使用,...

    C# 实现FTP客户端的小例子

    FtpHelper 是一个帮助类,提供了多种FTP操作的方法,例如上传文件、下载文件、删除文件等。FtpHelper 类通常与FtpWebRequest 类一起使用,来实现FTP客户端的功能。 知识点七: DownLoad 方法 DownLoad 方法是 ...

    C#实现FTP客户端的案例

    在本案例中,我们将探讨如何使用C#语言实现一个FTP(文件传输协议)客户端。FTP客户端允许用户与FTP服务器交互,执行...同时,这个案例也展示了如何结合Windows Forms控件和.NET框架提供的FTP相关类来构建桌面应用。

    DemoFtp.rar

    创建一个FTPHelper类,封装FTP连接、登录、下载等操作。这个类可以包含如下的方法: - `Connect(string host, string username, string password)`: 连接到FTP服务器。 - `Login()`: 使用提供的凭据登录FTP服务器...

    C#基类库大全

    6.FTP操作类 FTPClient FTPHelper FTPOperater 7.JS操作类 JsHelper 8.JSON 转化类 ConvertJson List转成Json|对象转成Json|集合转成Json|DataSet转成Json|DataTable转成Json|DataReader转成Json等 9.Mime Media...

    NetHelper_C#帮助类HtmlHelper_JSON_PostJson_

    1. **FtpHelper.cs**: 这可能是一个FTP(File Transfer Protocol)助手类,提供了上传、下载文件到FTP服务器的功能,这对于Web开发中的文件传输非常有用。 2. **SocketHelper.cs**: 这是基于套接字的网络通信助手类...

Global site tag (gtag.js) - Google Analytics