设为首页 收藏本站
查看: 2197|回复: 0

C#操作FTP总结

[复制链接]

尚未签到

发表于 2015-5-26 09:19:39 | 显示全部楼层 |阅读模式
  本文是对FTP相关操作,例如新建/删除目录、新建/删除文件、获取文件/目录列表等的总结,方便日后调用。
  其实C#操作FTP和操作本地文件/目录差不多,尤其是对动作而言,因为它们都是文件或目录,区别在于FTP可以是远程的文件或目录等,所以需要建立一个连接,当然由于是对FTP的请求,所以会要求从本地发起一个FtpWebRequest,当然这个请求中包含一些设置,例如:请求连接的信用凭证、数据的传输格式、以及请求的FTP动作等等,FTP服务器接收到这个请求后就会返回一个FtpWebResponse了。本来微软已经提供了操作FTP的一些方法,都在System.Net命名空间下,但是感觉用起来还是不是很方便,所以自己又总结了一下,权且当作是对一个简单地封装吧,方便以后再使用的时候可以拿来就用。
  由于这些方法都比较简单,而且每个方法我都加了中文注释,所以在此就不再赘述和分别描述了,直接上代码。



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
namespace PCT.FCL
{
    public class FTPHelper : IDisposable
    {
        public FTPHelper(string requestUriString, string userName, string password)
        {
            this.requestUriString = requestUriString;
            this.userName = userName;
            this.password = password;
        }
        private string requestUriString;
        private string userName;
        private string password;
        private FtpWebRequest request;
        private FtpWebResponse response;
        ///
        /// 创建FtpWebRequest
        ///
        /// FTP路径
        /// FTP方法
        private void OpenRequest(string uriString, string method)
        {
            this.request = WebRequest.Create(new Uri(this.requestUriString + uriString)) as FtpWebRequest;
            this.request.Credentials = new NetworkCredential(userName, password);
            this.request.UseBinary = true;
            this.request.Method = method;
        }
        ///
        /// 返回FtpWebResponse
        ///
        /// FTP路径
        /// FTP方法
        private void OpenResponse(string uriString, string method)
        {
            this.OpenRequest(uriString, method);
            this.response = this.request.GetResponse() as FtpWebResponse;
        }
        ///
        /// 创建目录
        ///
        /// 要创建的目录名称
        public void MakeDirectory(string directoryPath)
        {
            this.OpenResponse(directoryPath, WebRequestMethods.Ftp.MakeDirectory);
        }
        ///
        /// 删除目录
        ///
        /// 要删除的目录名称
        public void RemoveDirectory(string directoryPath)
        {
            this.OpenResponse(directoryPath, WebRequestMethods.Ftp.RemoveDirectory);
        }
        ///
        /// 重命名文件
        ///
        /// 原文件名
        /// 新文件名
        public void Rename(string originalFileName, string newFileName)
        {
            this.OpenResponse(originalFileName, WebRequestMethods.Ftp.Rename);
            this.request.RenameTo = newFileName;
            this.response = this.request.GetResponse() as FtpWebResponse;
        }
        ///
        /// 上传文件到服务器
        ///
        /// 要上传的本地文件全路径
        public void UploadFile(string localFullPath)
        {
            this.UploadFile(localFullPath, false);
        }
        ///
        /// 上传文件到服务器
        ///
        /// 要上传的本地文件全路径
        /// 是否要重写服务器上的文件
        public void UploadFile(string localFullPath, bool overWriteFile)
        {
            this.UploadFile(localFullPath, Path.GetFileName(localFullPath), overWriteFile);
        }
        ///
        /// 上传文件到服务器
        ///
        /// 要上传的本地文件全路径
        /// 上传后文件重命名为
        public void UploadFile(string localFullPath, string remoteFileName)
        {
            this.UploadFile(localFullPath, remoteFileName, false);
        }
        ///
        /// 上传文件到服务器
        ///
        /// 要上传的本地文件全路径
        /// 上传后文件重命名为
        /// 是否要重写服务器上的文件
        public void UploadFile(string localFullPath, string remoteFileName, bool overWriteFile)
        {
            byte[] fileBytes = null;
            using (FileStream fileStream = new FileStream(localFullPath, FileMode.Open, FileAccess.Read))
            {
                fileBytes = new byte[fileStream.Length];
                fileStream.Read(fileBytes, 0, (Int32)fileStream.Length);
            }
            this.UploadFile(fileBytes, remoteFileName, overWriteFile);
        }
        ///
        /// 上传文件到服务器
        ///
        /// 上传文件的字节流
        /// 上传后文件重命名为
        public void UploadFile(byte[] fileBytes, string remoteFileName)
        {
            this.UploadFile(fileBytes, remoteFileName, false);
        }
        ///
        /// 上传文件到服务器
        ///
        /// 上传文件的字节流
        /// 上传后文件重命名为
        /// 是否要重写服务器上的文件
        public void UploadFile(byte[] fileBytes, string remoteFileName, bool overWriteFile)
        {
            this.OpenResponse(overWriteFile ? remoteFileName : Gadget.ReturnFileNameWithCurrentDate(remoteFileName), WebRequestMethods.Ftp.UploadFile);
            using (Stream stream = this.request.GetRequestStream())
            {
                using (MemoryStream memoryStream = new MemoryStream(fileBytes))
                {
                    byte[] buffer = new byte[Constant.FTP.LenOfBuffer];
                    int bytesRead = 0;
                    int totalRead = 0;
                    while (true)
                    {
                        bytesRead = memoryStream.Read(buffer, 0, buffer.Length);
                        if (bytesRead == 0)
                        {
                            break;
                        }
                        totalRead += bytesRead;
                        stream.Write(buffer, 0, bytesRead);
                    }
                }
                this.response = this.request.GetResponse() as FtpWebResponse;
            }
        }
        ///
        /// 下载服务器文件到本地
        ///
        /// 要下载的服务器文件名
        /// 下载到本地的路径
        public void DownloadFile(string remoteFileName, string localPath)
        {
            this.DownloadFile(remoteFileName, localPath, false);
        }
        ///
        /// 下载服务器文件到本地
        ///
        /// 要下载的服务器文件名
        /// 下载到本地的路径
        /// 是否要重写本地的文件
        public void DownloadFile(string remoteFileName, string localPath, bool overWriteFile)
        {
            this.DownloadFile(remoteFileName, localPath, remoteFileName, overWriteFile);
        }
        ///
        /// 下载服务器文件到本地
        ///
        /// 要下载的服务器文件名
        /// 下载到本地的路径
        /// 下载到本地的文件重命名为
        public void DownloadFile(string remoteFileName, string localPath, string localFileName)
        {
            this.DownloadFile(remoteFileName, localPath, localFileName, false);
        }
        ///
        /// 下载服务器文件到本地
        ///
        /// 要下载的服务器文件名
        /// 下载到本地的路径
        /// 下载到本地的文件重命名为
        /// 是否要重写本地的文件
        public void DownloadFile(string remoteFileName, string localPath, string localFileName, bool overWriteFile)
        {
            byte[] fileBytes = this.DownloadFile(remoteFileName);
            if (fileBytes != null)
            {
                using (FileStream fileStream = new FileStream(Path.Combine(localPath, overWriteFile ? localFileName : Gadget.ReturnFileNameWithCurrentDate(localFileName)), FileMode.Create))
                {
                    fileStream.Write(fileBytes, 0, fileBytes.Length);
                    fileStream.Flush();
                }
            }
        }
        ///
        /// 下载服务器文件到本地
        ///
        /// 要下载的服务器文件名
        /// 文件的字节流
        public byte[] DownloadFile(string RemoteFileName)
        {
            this.OpenResponse(RemoteFileName, WebRequestMethods.Ftp.DownloadFile);
            using (Stream stream = this.response.GetResponseStream())
            {
                using (MemoryStream memoryStream = new MemoryStream(Constant.FTP.CapacityofMemeoryStream))
                {
                    byte[] buffer = new byte[Constant.FTP.LenOfBuffer];
                    int bytesRead = 0;
                    int TotalRead = 0;
                    while (true)
                    {
                        bytesRead = stream.Read(buffer, 0, buffer.Length);
                        TotalRead += bytesRead;
                        if (bytesRead == 0)
                            break;
                        memoryStream.Write(buffer, 0, bytesRead);
                    }
                    return memoryStream.Length > 0 ? memoryStream.ToArray() : null;
                }
            }
        }
        ///
        /// 删除服务器文件
        ///
        /// 要删除的文件路径
        /// 要删除的文件名
        public void DeleteFile(string directoryPath, string fileName)
        {
            this.DeleteFile(directoryPath + fileName);
        }
        ///
        /// 删除服务器文件
        ///
        /// 要删除的文件名
        public void DeleteFile(string fileName)
        {
            this.OpenResponse(fileName, WebRequestMethods.Ftp.DeleteFile);
        }
        ///
        /// 列出服务器上指定目录下的所有文件
        ///
        /// 指定的目录
        /// 文件名列表
        public string[] LisFiles(string directoryPath)
        {
            List filesList = new List();
            this.OpenResponse(directoryPath, WebRequestMethods.Ftp.ListDirectory);
            using (StreamReader streamReader = new StreamReader(this.response.GetResponseStream()))
            {
                return Gadget.SplitString(streamReader.ReadToEnd(), Constant.TextConstant.FtpNewLine);
            }
        }
        ///
        /// 列出服务器上指定目录下的所有子目录
        ///
        /// 指定的目录
        /// 子目录名列表
        public string[] ListDirectories(string directoryPath)
        {
            List directoriesList = new List();
            this.OpenResponse(directoryPath, WebRequestMethods.Ftp.ListDirectoryDetails);
            using (StreamReader streamReader = new StreamReader(this.response.GetResponseStream()))
            {
                string line = streamReader.ReadLine();
                if (line != null)
                {
                    while (line != null)
                    {
                        //line = drwxrwxrwx   1 user     group           0 Jul 15 18:17 Archive_20110714
                        line = line.Substring(line.LastIndexOf(Constant.TextConstant.Colon) + Constant.FTP.LenToDirectory);
                        if (!line.StartsWith(Constant.FileConstant.FileTypeSeperator))//remove the folder like . or ..
                        {
                            directoriesList.Add(line);
                        }
                        line = streamReader.ReadLine();
                    }
                    return directoriesList.ToArray();
                }
            }
            return null;
        }
        ///
        /// 检查指定的目录是否在服务器上存在
        ///
        /// 指定的目录
        /// 如果存在返回true,否则返回false
        public bool DirectoryExist(string directory)
        {
            try
            {
                this.OpenResponse(directory, WebRequestMethods.Ftp.GetDateTimestamp);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        ///
        /// 检查指定的文件是否在服务器上存在
        ///
        /// 指定的目录
        /// 指定的文件
        /// 如果存在返回true,否则返回false
        public bool FileExist(string directoryPath, string remoteFileName)
        {
            string[] fileNames = this.LisFiles(directoryPath);
            foreach (string fileName in fileNames)
            {
                if (string.Compare(fileName, remoteFileName, true) == 0)
                {
                    return true;
                }
            }
            return false;
        }
        ///
        /// 释放资源
        ///
        public void Dispose()
        {
            this.Close();
        }
        ///
        /// 释放资源
        ///
        public void Close()
        {
            if (this.response != null)
            {
                this.response.Close();
                this.response = null;
            }
        }
    }
}
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-70774-1-1.html 上篇帖子: 免费打造自己的个人网站,免费域名、免费空间、FTP、数据库什么的,一个不能少,没钱,也可以这么任性 下篇帖子: FTP文件操作之上传文件
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表