【.NET】FTP

namespace Test.FTP
{
    public class MyFtp
    {
        private bool _isKeepAlive;
        private string _password;
        private string _serverIp;
        private string _userId;
        private int bufferSize;
        private FtpWebRequest ftpRequest;
        private FtpWebResponse ftpResponse;
        private Stream ftpStream;

        public MyFtp(string ftpServerIp, string ftpUserId, string ftpPassWord)
        {
            this.ftpRequest = null;
            this.ftpResponse = null;
            this.ftpStream = null;
            this.bufferSize = 0x800;
            this._serverIp = ftpServerIp;
            this._password = ftpPassWord;
            this._userId = ftpUserId;
            this._isKeepAlive = false;
        }

        public MyFtp(string ftpServerIp, string ftpUserId, string ftpPassWord, bool isKeepAlive)
        {
            this.ftpRequest = null;
            this.ftpResponse = null;
            this.ftpStream = null;
            this.bufferSize = 0x800;
            this._serverIp = ftpServerIp;
            this._password = ftpPassWord;
            this._userId = ftpUserId;
            this._isKeepAlive = isKeepAlive;
        }

        private void Connect()
        {
            this.ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + this._serverIp));
            this.ftpRequest.UseBinary = true;
            this.ftpRequest.UsePassive = true;
            this.ftpRequest.KeepAlive = _isKeepAlive;
            this.ftpRequest.Credentials = new NetworkCredential(this._userId, this._password);
        }

        private void Connect(string path)
        {
            this.ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(path));
            this.ftpRequest.UseBinary = true;
            this.ftpRequest.UsePassive = true;
            this.ftpRequest.KeepAlive = _isKeepAlive;
            this.ftpRequest.Credentials = new NetworkCredential(this._userId, this._password);
        }

        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="dirName"></param>
        /// <returns></returns>
        public bool CreateDirectory(string dirName)
        {
            try
            {
                this.Connect("ftp://" + this._serverIp + "/" + dirName);
                this.ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
                this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse();
                this.ftpResponse.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="deleteFile"></param>
        /// <returns></returns>
        public bool Delete(string deleteFile)
        {
            try
            {
                this.Connect("ftp://" + this._serverIp + "/" + deleteFile);
                this.ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse();
                this.ftpResponse.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="dirName"></param>
        /// <returns></returns>
        public bool DeleteDirectory(string dirName)
        {
            try
            {
                this.Connect("ftp://" + this._serverIp + "/" + dirName);
                this.ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
                this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse();
                this.ftpResponse.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="remoteFile"></param>
        /// <param name="LocalFile"></param>
        /// <returns></returns>
        public bool DownLoad(string remoteFile, string LocalFile)
        {
            bool isSuccess;
            try
            {
                this.DownLoadContent(remoteFile, LocalFile);
                isSuccess = true;
            }
            catch (Exception)
            {
                try
                {
                    this.DownLoadContent(remoteFile, LocalFile);
                    isSuccess = true;
                }
                catch (Exception)
                {
                    isSuccess = false;
                }
            }

            return isSuccess;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="remoteFile"></param>
        /// <param name="LocalFile"></param>
        /// <returns></returns>
        public bool UpLoad(string remoteFile, string LocalFile)
        {
            bool isSuccess;
            try
            {
                this.UploadContent(remoteFile, LocalFile);
                isSuccess = true;
            }
            catch (Exception)
            {
                try
                {
                    this.UploadContent(remoteFile, LocalFile);
                    isSuccess = true;
                }
                catch (Exception)
                {
                    isSuccess = false;
                }
            }

            return isSuccess;
        }

        public string[] GetSimpleFileList(string remoteFile)
        {
            try
            {
                this.Connect("ftp://" + this._serverIp + "/" + remoteFile);

                StringBuilder sb = new StringBuilder();
                this.ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;

                this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse();
                this.ftpStream = this.ftpResponse.GetResponseStream();

                StreamReader ftpReader = new StreamReader(ftpStream);

                try
                {
                    while (ftpReader.Peek() != -1)
                    {
                        sb.Append(ftpReader.ReadLine());
                        sb.Append("|");
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                }

                ftpReader.Close();
                this.ftpStream.Close();
                this.ftpResponse.Close();
                return sb.ToString().Split(new char[] { ‘|‘ });
            }

            catch (Exception EX)
            {
                Console.WriteLine(EX.ToString());
                return null;
            }
        }

        private void DownLoadContent(string remoteFile, string localFile)
        {
            this.Connect("ftp://" + this._serverIp + "/" + remoteFile);
            this.ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            using (this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse())
            {
                using (this.ftpStream = this.ftpResponse.GetResponseStream())
                {
                    this.ftpStream.ReadTimeout = 0x1d4c0;
                    using (FileStream localStream = new FileStream(localFile, FileMode.Create))
                    {
                        byte[] buffer = new byte[this.bufferSize];
                        for (int bytesRead = this.ftpStream.Read(buffer, 0, this.bufferSize); bytesRead > 0; bytesRead = this.ftpStream.Read(buffer, 0, this.bufferSize))
                        {
                            localStream.Write(buffer, 0, bytesRead);
                        }
                    }

                }
            }
        }

        private void UploadContent(string remoteFile, string localFile)
        {
            FileInfo fileInfo = new FileInfo(localFile);
            this.Connect("ftp://" + this._serverIp + "/" + remoteFile);
            this.ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            this.ftpRequest.ContentLength = fileInfo.Length;

            using (FileStream stream = fileInfo.OpenRead())
            {
                byte[] byteBuffer = new byte[this.bufferSize];

                int contentLen = 0;
                using (this.ftpStream = this.ftpRequest.GetRequestStream())
                {
                    for (contentLen = stream.Read(byteBuffer, 0, this.bufferSize); contentLen != 0; contentLen = stream.Read(byteBuffer, 0, bufferSize))
                    {
                        this.ftpStream.Write(byteBuffer, 0, contentLen);
                    }
                }
            }
        }

        /// <summary>
        /// 重命名文件
        /// </summary>
        /// <param name="currentFileNameAndPath"></param>
        /// <param name="newFileName"></param>
        /// <returns></returns>
        public bool Rename(string currentFileNameAndPath, string newFileName)
        {
            try
            {
                this.Connect("ftp://" + this._serverIp + "/" + currentFileNameAndPath);
                this.ftpRequest.Method = WebRequestMethods.Ftp.Rename;
                this.ftpRequest.RenameTo = "/" + newFileName;
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                this.ftpResponse.Close();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }
    }
}
时间: 2024-11-06 07:09:06

【.NET】FTP的相关文章

【linux】——FTP出现500 OOPS: cannot change directory的解决方法

cannot change directory:/home/*** ftp服务器连接失败,错误提示: 500 OOPS: cannot change directory:/home/******* 500 OOPS: child died 解决方法: 在终端输入命令: setsebool -P ftpd_disable_trans 1 service vsftpd restart 就OK了! 原因:这是因为服务器开启了selinux,这限制了FTP的登录.

【转】ftp的两种模式

原文链接 http://net.chinaunix.net/5/2007/04/13/1144062.shtml ftp是基于tcp的服务,ftp使用2个端口,一个数据端口和一个命令端口(也叫做控制端口).通常命令端口是21,数据端口是20. 主动ftp 主动模式的ftp是这样的:客户端从一个任意的非特权端口n(n>1024)连接到ftp服务器的命令端口(21),然后客户端开始监听端口n+1,并发送ftp命令“port n+1”到ftp服务器.服务器从它自己的数据端口20连接到客户端指定的数据端

【Linux】 ftp 主动被动模式

LNMP 搭建得服务器,在使用ftp时候,报如下错误: 经查,是ftp 主动模式被动模式问题 工具:  Xftp5   ,把被动模式勾 取消 (其他客户端可以网上查一下 相应的 被动模式转主动模式设置方法) 还有一点: 把本地防火墙关了  !!!   因为这个原因.我找了半天,问了好多小伙伴,都不行,最后把本地防火墙关了.可以了 补充学习: ftp FTP主动模式和被动模式的比较 FTP是仅基于TCP的服务,不支持UDP.与众不同的是FTP使用2个端口,一个数据端口和一个命令端口(也可叫做控制端

【python】ftp连接,主被动,调试等级

示例代码如下: #!/usr/bin/env python # -*- coding: utf-8 -*- import os from ftplib import FTP def ftp_down(filename = "xx.tar.gz"): ftp=FTP() ftp.set_debuglevel(2) #设置调试等级 ftp.connect('127.0.0.1','21') ftp.login('user','passwd') ftp.set_pasv(False) #Fa

【 VSFTPD 】ftp 客户端问题

网络环境: 两个独立的内网环境,前端都有路由和防火墙的管控.要在这两个独立的内网使用ftp通过互联网进行通信. 首先,ftp server 服务端口默认修改为:2100 数据端口修改为:21000 将这两个内网服务器端口通过路由映射到公网端口. ftp server 使用的vsftpd的被动模式. 被动模式: 命令连接: 客户端大于1024端口 --> 服务器端21端口 数据连接: 客户端大于1024端口 --> 服务器端被动端口 我这里 FTP默认端口2100  数据端口设置为21000 

【转】 ftp运行的两种模式——xinetd运行模式和 standalone模式

ftp运行的两种模式——xinetd运行模式和 standalone模式 原文链接 http://blog.chinaunix.net/uid-22889411-id-59432.html 像其它守护程序一样,vsftpd提供了standalone和inetd(inetd或xinetd)两种运行模式.简单解释一下, standalone一次性启动,运行期间一直驻留在内存中,优点是对接入信号反应快,缺点是损耗了一定的系统资源,因此经常应用于对实时反应要求较高的专业FTP服务器.inetd恰恰相反,

【转】FTP主动模式和被动模式的比较

总是记不住FTP主动和被动模式的区别.放在这里,以备日后查阅. FTP是仅基于TCP的服务,不支持UDP.与众不同的是FTP使用2个端口,一个数据端口和一个命令端口(也可叫做控制端口).通常来说这两个端口是21(命令端口)和20(数据端口).但FTP工作方式的不同,数据端口并不总是20.这就是主动与被动FTP的最大不同之处. (一)主动FTP          主动方式的FTP是这样的:客户端从一个任意的非特权端口N(N>1024)连接到FTP服务器的命令端口,也就是21端口.然后客户端开始监听

【Debian】ftp安装

http://www.2cto.com/os/201107/98311.html http://jingyan.baidu.com/article/adc815133476bdf723bf7393.html vsftpd的配置ftp的配置文件主要有三个,在centos5.6中位于/etc/vsftpd/目录下,分别是:ftpusers    该文件用来指定那些用户不能访问ftp服务器.user_list   该文件用来指示的默认账户在默认情况下也不能访问ftpvsftpd.conf   vsft

【wget】wget的ftp相关功能

[wget下载ftp中的文件]wget的ftp相关功能 saveto=文件保存路径 URL=ftp路径 wgetlog=wget日志文件路径 wget -P ${saveto} --ftp-user=xxx --ftp-password=xxx -m -c -t5 ${URL} -a ${wgetlog} -nv        -o logfile        --output-file=logfile            Log all messages to logfile.  The