C# FTPHelper 支持多层级文件上传下载

在网上找了很多代码总觉得不能满足现有的需求 ,比如多级文件夹,一次性上传不同层级的所有文件。自己将网上找到的代码加上自己的修改。现在贴出来给大家希望呢个对大家有个小小帮助。欢迎找茬,互相进步

    /// <summary>
    /// FTP帮助类
    /// </summary>
    public class FTPHelper
    {
        #region 字段
        string ftpURI;
        string ftpUserID;
        string ftpServerIP;
        string ftpPassword;
        string ftpRemotePath;
        #endregion

        /// <summary>
        /// 连接FTP服务器
        /// </summary>
        /// <param name="FtpServerIP">FTP连接地址</param>
        /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
        /// <param name="FtpUserID">用户名</param>
        /// <param name="FtpPassword">密码</param>
        public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
        {
            this.ftpServerIP = FtpServerIP;
            this.ftpRemotePath = FtpRemotePath;
            this.ftpUserID = FtpUserID;
            this.ftpPassword = FtpPassword;
            this.ftpURI = "ftp://" + ftpServerIP + "/" + FtpRemotePath + "/";
        }

        /// <summary>
        /// 上传
        /// </summary>
        public void Upload(string filename, string ftpRemotePath)
        {
            FileInfo fileInf = new FileInfo(filename);
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + "/" + ftpRemotePath + "/" + fileInf.Name));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.KeepAlive = false;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileInf.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 下载
        /// </summary>
        public void Download(string localPath, string ftpRemotePath)
        {
            try
            {
                FileStream outputStream = new FileStream(localPath, FileMode.Create);
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpRemotePath));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        public void Delete(string fileName)
        {
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                reqFTP.KeepAlive = false;
                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 获取当前目录下明细(包含文件和文件夹)
        /// </summary>
        public string[] GetFilesDetailList()
        {
            try
            {
                StringBuilder result = new StringBuilder();
                FtpWebRequest ftp;
                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
                ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                //line = reader.ReadLine();
                //line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf("\n"), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 获取FTP文件列表(包括文件夹)
        /// </summary>
        public string[] GetAllList(string url)
        {
            List<string> list = new List<string>();
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(ftpURI + url));
            req.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            req.Method = WebRequestMethods.Ftp.ListDirectory;
            req.UseBinary = true;
            req.UsePassive = true;
            try
            {
                using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                    {
                        string s;
                        while ((s = sr.ReadLine()) != null)
                        {
                            list.Add(s);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            return list.ToArray();
        }

        /// <summary>
        /// 获取当前目录下文件列表(不包括文件夹)
        /// </summary>
        public string[] GetFileList(string url)
        {
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + url));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {

                    if (line.IndexOf("<DIR>") == -1)
                    {
                        result.Append(Regex.Match(line, @"[\S]+ [\S]+", RegexOptions.IgnoreCase).Value.Split(' ')[1]);
                        result.Append("\n");
                    }
                    line = reader.ReadLine();
                }
                if (result.Length > 0)
                {
                    result.Remove(result.ToString().LastIndexOf('\n'), 1);
                }
                reader.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            return result.ToString().Split('\n');
        }

        /// <summary>
        /// 获取所有文件路径 递归(包括子目录文件)
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public string[] GetAllFileList(string dir)
        {
            List<string> list = new List<string>();
            string[] filelist = GetAllList(dir);

            for (int i = 0; i < filelist.Length; i++)
            {
                var filepath = filelist[i];
                //判断是否是文件
                bool istrue = FileExist(dir + "\\" + filepath);
                if (istrue)
                {
                    list.Add(dir + "\\" + filepath);
                }
                else
                {
                    var dir2 = dir + "\\" + filepath;
                    var list1 = GetAllFileList(dir2);
                    for (int j = 0; j < list1.Length; j++)
                    {
                        list.Add(list1[j]);
                    }

                }
            }
            return list.ToArray();

        }

        /// <summary>
        /// 判断当前目录下指定的文件是否存在
        /// </summary>
        /// <param name="RemoteFileName">远程文件名</param>
        public bool FileExist(string RemoteFileName)
        {
            var request = (FtpWebRequest)WebRequest.Create(ftpURI + RemoteFileName);
            request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            request.Method = WebRequestMethods.Ftp.GetFileSize;
            try
            {
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 检测目录是否存在
        /// </summary>
        /// <param name="dir"></param>
        /// <returns>false不存在,true存在</returns>
        private bool DirectoryIsExist(string dir)
        {
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dir));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
            reqFTP.UseBinary = true;
            try
            {
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                string e = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        public void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            { }
        }

        /// <summary>
        /// 获取指定文件大小
        /// </summary>
        public long GetFileSize(string filename)
        {
            FtpWebRequest reqFTP;
            long fileSize = 0;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            { }
            return fileSize;
        }

        /// <summary>
        /// 更改文件名
        /// </summary>
        public void ReName(string currentFilename, string newFilename)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            { }
        }

        /// <summary>
        /// 移动文件
        /// </summary>
        public void MovieFile(string currentFilename, string newDirectory)
        {
            ReName(currentFilename, newDirectory);
        }

        /// <summary>
        /// 切换当前目录
        /// </summary>
        /// <param name="IsRoot">true:绝对路径 false:相对路径</param>
        public void GotoDirectory(string DirectoryName, bool IsRoot)
        {
            if (IsRoot)
            {
                ftpRemotePath = DirectoryName;
            }
            else
            {
                ftpRemotePath += DirectoryName + "/";
            }
            ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
        }

    }

时间: 2024-11-01 15:42:59

C# FTPHelper 支持多层级文件上传下载的相关文章

开源项目OkHttpPlus——支持GET、POST、UI线程回调、JSON格式解析、链式调用、文件上传下载

OkHttpPlus介绍 项目地址:https://github.com/ZhaoKaiQiang/OkHttpPlus 主要功能:OkHttp封装,支持GET.POST.UI线程回调.JSON格式解析.链式调用.小文件上传下载及进度监听等功能 为什么要写这么一个库呢? 首先,是因为OkHttp在4.4之后已经作为底层的Http实现了,所以OkHttp这个库很强大,值得我们学习. 其次,在我看来,OkHttp使用起来不如Volley方便,OkHttp的回调都是在工作线程,所以如果在回调里面操作V

【FTP】FTP文件上传下载-支持断点续传

Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常用)]和[ASCII_FILE_TYPE]两种; 数据连接模式:一般使用LocalPassiveMode模式,因为大部分客户端都在防火墙后面: 1. LocalPassiveMode:服务器端打开数据端口,进行数据传输: 2. LocalActiveMode:客户端打开数据端口,进行数据传输: 系统

java web 文件上传下载

文件上传下载案例: 首先是此案例工程的目录结构: 处理上传: FileUploadServlet.java 1 package fnz.fileUploadTest; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.PrintWriter; 7 import java.text.SimpleDateFormat; 8 import java.

Struts2学习之文件上传/下载&amp;ValueStack(三)

简介 今天是学习Struts2第三天,也算struts2准备前奏告一段落,提升部分只能在后期深入了解,多看源码,多参阅资料.今天所学的知识点文件上传.下载/ValueStack&OGNL/Struts2标签 文件上传/下载 文件上传简介 a). 企业常用文件上传技术 : jspSmartUpload(主要应用 JSP model1 时代) . fileupload (Apache commons项目中一个组件). Servlet3.0 集成文件上传 Part类 b). Struts2 对文件上传

javaEE(10)_文件上传下载

一.文件上传概述 1.实现web开发中的文件上传功能,需完成如下二步操作: •在web页面中添加上传输入项•在servlet中读取上传文件的数据,并保存到本地硬盘中. 2.如何在web页面中添加上传输入项?    <input type=“file”>标签用于在web页面中添加文件上传输入项,设置文件上传输入项时须注意:•必须要设置input输入项的name属性,否则浏览器将不会发送上传文件的数据.•必须把form的enctype属值设为multipart/form-data.设置该值后,浏览

Selenium2学习-039-WebUI自动化实战实例-文件上传下载

通常在 WebUI 自动化测试过程中必然会涉及到文件上传的自动化测试需求,而开发在进行相应的技术实现是不同的,粗略可划分为两类:input标签类(类型为file)和非input标签类(例如:div.a或其他方式结合实现). 非input标签类因其有各式各样的实现方式,需要考虑具体的场景,因而此文对此类文件上传不做讲解,以input标签实现文件上传的方式进行讲解,请知悉! 解决方案有如下三种: 1.定位元素直接通过sendkeys修改input标签的文件链接: 2.通过第三方控件(AutoIt)编

NSURLSession(Get &amp; Post,JSON、XML数据解析,文件上传下载)

NSURLSession(Get & Post,JSON.XML数据解析,文件上传下载) 一.NSURLSession概述 NSURLSession是iOS7中新的网络接口,支持后台网络操作,除非用户强行关闭. NSURLSession使用步骤: 1. 新建NSURLSessionConfiguration,用于NSURLSession的配置 2. 新建NSURLSession 3. 新建NSURLSessionTask对象 4. 执行task 其中NSURLSessionConfigurati

关于使用SecureCRT 实现 WIN7 与 Linux 双向通信的问题及文件上传下载

Linux 版本:Cent 6.5 X86 VMware workstation 10.0 win7 Ultimate x86 ,Linux 均可以正常链接网络[采用桥接方式] 遇到问题: win7 可以 ping 通linux及网关,linux不能ping通网关及win7,但能链接网络. 前提: 需要手动配置linux的IP为静态,WIN7的可以随意,但是一般在一个网段(不然配置较复杂了),保证可以正常通信访问. 解决: 通过手动改ip及相关配置的方法之后,仍然未能ping通,改链接方式为NA

文件上传表单 上传文件的细节 文件上传下载和数据库结合

1 文件上传表单   1)上传文件的本质是文本复制的过程   2)技术层面,在Java中一定会用到IO操作,主要以二进制方式读写   3)传统方式下,对于上传文件字段不同的浏览器有着不同的解析方式,例如:     IE6:upfile=c:\aa\bb\a.JPG     非IE6: upfile=a.JPG   4)可以将form以MIME协议的方式将上传文件传递到服务端,服务端以二进制流的方式读写     代码:客户端form enctype="multipart/form-data&quo