首页 > 其他分享 >.NET FTPHelper

.NET FTPHelper

时间:2023-01-04 17:11:48浏览次数:37  
标签:string FTPHelper Close var new NET reqFTP response

using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;

namespace Demo
{
    public class FtpHepler
    {
        private string ftpPassword = ConfigurationManager.AppSettings["FtpPassWord"];
        private string ftpServerIP = ConfigurationManager.AppSettings["FtpIp"];
        private string ftpUserID = ConfigurationManager.AppSettings["FtpUser"];
        private string ftpRemotePath;
        private string ftpURI;

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

        //public FtpHepler(string FtpRemotePath,int jsType)
        //{
        //    if (jsType!=0)
        //    {
        //        this.ftpPassword  = ConfigurationManager.AppSettings["JsFtpPassWord"];
        //        this.ftpServerIP = ConfigurationManager.AppSettings["JsFtpIp"];
        //        this.ftpUserID = ConfigurationManager.AppSettings["JsFtpUser"];
        //    }
            
        //    ftpRemotePath = FtpRemotePath;
        //    ftpURI = "ftp://" + ftpServerIP + "/";
        //    if (!string.IsNullOrEmpty(ftpRemotePath))
        //    {
        //        ftpURI = ftpURI + ftpRemotePath.Trim('/') + "/";
        //    }
        //}



        public string GetFtpURI()
        {
            return ftpURI;
        }

        /// <summary>
        ///     上传
        /// </summary>
        /// <param name="filename"></param>
        public void Upload(string filename)
        {
            var fileInf = new FileInfo(filename);
            var uri = ftpURI + fileInf.Name;
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.KeepAlive = false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileInf.Length;
            var buffLength = 2048;
            var buff = new byte[buffLength];
            int contentLen;
            var fs = fileInf.OpenRead();
            try
            {
                var 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)
            {
                Conwin.Framework.Log4net.LogHelper.Error("FTP上传失败",ex);
            }
        }

        /// <summary>
        ///     上传
        /// </summary>
        /// <param name="filename"></param>
        public void Upload(byte[] stream, string FtpRemotePath)
        {
            var uri = ftpURI + FtpRemotePath;
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.KeepAlive = false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = stream.Length;
            try
            {
                using (var strm = reqFTP.GetRequestStream())
                {
                    strm.Write(stream, 0, stream.Length);
                }
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        ///     上传
        /// </summary>
        /// <param name="filename"></param>
        public void Upload(Stream stream, string FtpRemotePath)
        {
            var uri = ftpURI + FtpRemotePath;
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.KeepAlive = false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = stream.Length;
            var buffLength = 2048;
            var buff = new byte[buffLength];
            int contentLen;

            try
            {
                var strm = reqFTP.GetRequestStream();
                contentLen = stream.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = stream.Read(buff, 0, buffLength);
                }
                strm.Close();
                stream.Close();
            }
            catch (Exception ex)
            {
                Conwin.Framework.Log4net.LogHelper.Error("FTP上传失败", ex);
            }
        }

        /// <summary>
        ///     上传
        /// </summary>
        /// <param name="filename"></param>
        public void Upload(MemoryStream stream, string FtpRemotePath)
        {
            var uri = ftpURI + FtpRemotePath;
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.KeepAlive = false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = stream.Length;
            try
            {
                stream.Position = 0;
                var strm = reqFTP.GetRequestStream();
                stream.CopyTo(strm);
                strm.Close();
                stream.Close();
            }
            catch (Exception ex)
            {
                Conwin.Framework.Log4net.LogHelper.Error("FTP上传失败", ex);
            }
        }

        /// <summary>
        ///     下载
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public string Download(string filePath, string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                var outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);

                reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                var response = (FtpWebResponse) reqFTP.GetResponse();
                var ftpStream = response.GetResponseStream();
                var cl = response.ContentLength;
                var bufferSize = 2048;
                int readCount;
                var 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)
            {
                return fileName + " 下载失败 --> " + ex.Message;
            }

            return string.Empty;
        }

        /// <summary>
        ///     下载
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public string Download1(string fileName, ref byte[] base64string)
        {
            FtpWebRequest reqFTP;
            Stream ftpStream = null;
            FtpWebResponse response = null;
            MemoryStream outputStream = null;
            try
            {
                outputStream = new MemoryStream();

                reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                response = (FtpWebResponse) reqFTP.GetResponse();
                ftpStream = response.GetResponseStream();
                var cl = response.ContentLength;
                var bufferSize = 2048;
                int readCount;
                var buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                base64string = outputStream.ToArray();
                //ftpStream.Close();
                //outputStream.Close();
                //response.Close();
            }
            catch (Exception ex)
            {
                return fileName + " 下载失败 --> " + ex.Message;
            }
            finally
            {
                ftpStream?.Close();
                outputStream?.Close();
                response?.Close();
            }

            return string.Empty;
        }

        /// <summary>
        ///     将流转化为二进制数组
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public byte[] StreamToBytes(Stream stream)
        {
            var bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始     
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        /// <summary>
        ///     下载
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public string Download(string fileName, ref byte[] base64string)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                var response = (FtpWebResponse) reqFTP.GetResponse();
                var ftpStream = response.GetResponseStream();
                var cl = response.ContentLength;
                var bufferSize = base64string.Length;
                base64string = new byte[bufferSize];

                ftpStream.Read(base64string, 0, bufferSize);

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                return fileName + " 下载失败 --> " + ex.Message;
            }

            return string.Empty;
        }

        /// <summary>
        ///     删除文件
        /// </summary>
        /// <param name="fileName"></param>
        public string Delete(string fileName)
        {
            try
            {
                var uri = ftpURI + fileName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri));

                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                var result = string.Empty;
                var response = (FtpWebResponse) reqFTP.GetResponse();
                var size = response.ContentLength;
                var datastream = response.GetResponseStream();
                var sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                return "删除失败 --> " + ex.Message + "  文件名:" + fileName;
            }

            return string.Empty;
        }

        /// <summary>
        ///     删除文件夹
        /// </summary>
        /// <param name="folderName"></param>
        public void RemoveDirectory(string folderName)
        {
            try
            {
                var uri = ftpURI + folderName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri));

                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;

                var result = string.Empty;
                var response = (FtpWebResponse) reqFTP.GetResponse();
                var size = response.ContentLength;
                var datastream = response.GetResponseStream();
                var sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        ///     获取当前目录下明细(包含文件和文件夹)
        /// </summary>
        /// <returns></returns>
        public string[] GetFilesDetailList()
        {
            string[] downloadFiles;
            try
            {
                var result = new StringBuilder();
                FtpWebRequest ftp;
                ftp = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI));
                ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                var response = ftp.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), Encoding.Default);

                //while (reader.Read() > 0)
                //{

                //}
                var line = reader.ReadLine();
                //line = reader.ReadLine();
                //line = reader.ReadLine();

                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                if (!string.IsNullOrWhiteSpace(result.ToString()))
                {
                    result.Remove(result.ToString().LastIndexOf("\n"), 1);
                    return result.ToString().Split('\n');
                }
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        ///     获取当前目录下文件列表(仅文件)
        /// </summary>
        /// <returns></returns>
        public string[] GetFileList(string mask)
        {
            var result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                var response = reqFTP.GetResponse();

                var reader = new StreamReader(response.GetResponseStream(), Encoding.Default);

                var line = reader.ReadLine();
                while (line != null)
                {
                    //if (line.ToLower().IndexOf(mask) > 0)
                    //{
                    result.Append(line);
                    result.Append("\n");
                    //}
                    //if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
                    //{
                    //    string mask_ = mask.Substring(0, mask.IndexOf("*"));
                    //    if (line.Substring(0, mask_.Length) == mask_)
                    //    {
                    //        result.Append(line);
                    //        result.Append("\n");
                    //    }
                    //}
                    //else
                    //{
                    //    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)
            {
                Conwin.Framework.Log4net.LogHelper.Fatal("filehelp",ex);
                throw ex;
                return null;
            }
        }

        /// <summary>
        ///     获取当前目录下所有的文件夹列表(仅文件夹)
        /// </summary>
        /// <returns></returns>
        public string[] GetDirectoryList()
        {
            var drectory = GetFilesDetailList();
            var m = string.Empty;
            if (drectory != null)
            {
                foreach (var str in drectory)
                {
                    var dirPos = str.IndexOf("<DIR>");
                    if (dirPos > 0)
                    {
                        /*判断 Windows 风格*/
                        m += str.Substring(dirPos + 5).Trim() + "\n";
                    }
                    else if (str.Trim().Substring(0, 1).ToUpper() == "D")
                    {
                        /*判断 Unix 风格*/
                        //string dir = str.Substring(54).Trim();
                        var dir = str.Substring(49).Trim();
                        if (dir != "." && dir != "..")
                        {
                            m += dir + "\n";
                        }
                    }
                }

                char[] n = {'\n'};
                return m.Split(n);
            }
            return null;
        }

        /// <summary>
        ///     判断当前目录下指定的子目录是否存在
        /// </summary>
        /// <param name="RemoteDirectoryName">指定的目录名</param>
        public bool DirectoryExist(string RemoteDirectoryName)
        {
            var dirList = GetDirectoryList();
            if (dirList != null)
            {
                foreach (var str in dirList)
                {
                    if (str.Trim() == RemoteDirectoryName.Trim())
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        /// <summary>
        ///     判断当前目录下指定的文件是否存在
        /// </summary>
        /// <param name="RemoteFileName">远程文件名</param>
        public bool FileExist(string RemoteFileName)
        {
            var fileList = GetFileList("*.*");
            foreach (var str in fileList)
            {
                if (str.Trim() == RemoteFileName.Trim())
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        ///     创建文件夹
        /// </summary>
        /// <param name="dirName"></param>
        public void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                // dirName = name of the directory to create.
                reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                var response = (FtpWebResponse) reqFTP.GetResponse();
                var ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        ///     获取指定文件大小
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public long GetFileSize(string filename)
        {
            FtpWebRequest reqFTP;
            long fileSize = 0;
            try
            {
                reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + filename));
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                var response = (FtpWebResponse) reqFTP.GetResponse();
                var ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
            }
            return fileSize;
        }

        /// <summary>
        ///     改名
        /// </summary>
        /// <param name="currentFilename"></param>
        /// <param name="newFilename"></param>
        public void ReName(string currentFilename, string newFilename)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + currentFilename));
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                var response = (FtpWebResponse) reqFTP.GetResponse();
                var ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
            }
        }

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

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

 

标签:string,FTPHelper,Close,var,new,NET,reqFTP,response
From: https://www.cnblogs.com/ZeroSunny/p/17025448.html

相关文章

  • .net core
      异步方法,不会缩短单个程序的服务时间,对于不支持异步方法的函数,有返回值的,可以用result来获取方法的返回值;无返回值的,可以用wait(),但是容易造成死锁......
  • Netty面试题及答案整理(2023最新版)
    **Netty面试题及答案**,每道都是认真筛选出的高频面试题,助力大家能找到满意的工作!###**下载链接**:[**全部面试题及答案PDF**](https://gitee.com/woniu201/interview-refere......
  • sun.security.validator.ValidatorException: PKIXpath building failed: sun.securit
    报错信息:javax.net.ssT.SSLHandshakeExceptions.certpath.SunCertPathBuilderException:unabletofindvalidcertificationpathtoreguestedtarget问题描述:在ja......
  • C#版本与.NET版本对应关系以及各版本的特性
      C#版本.NET版本发布日期特性C#1.0.NETFramework1.02002-02-13委托、事件C#1.1.NETFramework1.12003-04-24APM(异步编程模型)C#2.0.NETFram......
  • C#与.NET的关系
     C# 全称(Csharp),C#是由C和C++衍生出来的一种安全的、稳定的、简单的、优雅的面向对象编程语言。是一种编程语言,可以开发基于.net平台的应用。 C#的特点1、语法简洁......
  • NET2272.C 代码分析——InitProcessorSpecificConfiguration
    函数定义如下:section("L1_code")intInitProcessorSpecificConfiguration(ADI_NET2272_DEVICE*pDev){unsignedshortusValue;volatileunsignedintv;#ifdefined......
  • NET2272.C 代码分析——SetProcessorSpecificDefaultConfiguration
    section("L1_code")intSetProcessorSpecificDefaultConfiguration(ADI_NET2272_DEVICE*pDev){/*enableasyncbank3*/*pEBIU_AMGCTL|=0xF;ssync();/*defau......
  • Netty-架构设计及入门程序-3
    一、原生NIO存在的问题1、NIO的类库和API繁杂,使用麻烦:需要熟练掌握Selector、ServerSocketChannel、SocketChannel、ByteBuffer等。2、需要具备其他的额外技能:要熟......
  • S7.NET —— 简单使用
    2023-01-04 最近想写个与PLC通讯的程序,找到了S7.NET,简单记录下使用方法用途:与西门子PLC通讯流程:创建连接——读/写数据——关闭连接1.添加引用usingS7.Net;2.......
  • VS2022中ArcGIS Pro SDK for .NET安装和卸载指南
    VS2022中ArcGISProSDKfor.NET安装和卸载指南   安裝ArcGISProSDKfor.NET   升级ArcGISProSDKfor.NET   卸载ArcGISProSDKfor.NET   使......