当前位置:网站首页>C# ftpHelper

C# ftpHelper

2022-04-23 21:26:00 Plant a sweet smell

@C# ftp File action class ftpHelper

C# ftp File action class ftpHelper:

stay C# When operating on files , Search Baidu and Bing for a lot of information , But there is no perfect operation ftp Of documents ftpHelper class , What other students wrote is inevitably somewhat unsatisfactory , Then I want to write a perfect ftp File action class ftpHelper. These methods are following Ah Ben, play together NET Expand and organize on the basis of , All methods have been verified , Safe to use . If there is something to explore , Just leave me a message .

ftpHelper Operation class reference description

1. Most of the content of the article is from https://cloud.tencent.com/developer/article/1343559 What you see here , I have added several methods above , And optimize the return content ;
2. For all methods , I have been verified , Safe to use ;
3. If you think this ftpHelper Can also be the , Want to give me some praise at the same time , Please don't forget to quote me " Play with ah Beng NET" give the thumbs-up , thank you ;
4. I upload the specific verification to CSDN,0 Currency download , Download link FtpHepler Operation class download ;
5. If the Windows FileHepler Interested in , You can click on the FileHepler download

The main method :

ftp Several main methods of operation

1.FTP initialization ;
2. Create directory ;
3. Change directory or file name ;
4. Switch the current directory ;
5. List all files in the current directory ;
6. List all first level subdirectories of the current directory ;
7. Judge whether the specified subdirectory or file in the current directory exists ;
8. Judge whether the specified sub file in the current directory exists ;
9. Delete empty directory ;
10. Delete directory ( Include all subdirectories and sub files below )
11. Delete file ;
12. Download a single file ;
13. Batch download all files and directories in the current directory ;
14. Single file upload ;
15. Batch upload all files in the current directory ;
16. Recursive get FTP Directory and file information on the server ;
17. Get the files and folders in the current directory ;
18. Get the first level word directory and file information of the current directory ;

Main screenshots :

1. Download Interface ,0 Currency download
0 Currency download

2. Verification function interface
 Insert picture description here
3.FtpHepler Content
 Insert picture description here

 Insert picture description here

Code content

/// <summary>
    /// FTP Operation class 
    /// </summary>
    public class FtpHelper
    {
    
        /// <summary>
        /// FTP Request object 
        /// </summary>
        FtpWebRequest request = null;
        /// <summary>
        /// FTP The response object 
        /// </summary>
        FtpWebResponse response = null;

        /// <summary>
        ///  The contents of the document 
        /// </summary>
        List<FileStruct> fileLists = new List<FileStruct>();

        /// <summary>
        ///  Multiple message entities 
        /// </summary>
        List<OperationResult> operationResults = new List<OperationResult>();

        /// <summary>
        ///  A single message entity 
        /// </summary>
        OperationResult operationResult = new OperationResult();

        FilesHelper filesHelper = new FilesHelper();

        public string ftpServerIP;          //FTPIP
        public string ftpServerPort;        //FTP port 
        public string ftpRemotePath;        //FTP Target directory 
        public string ftpUserID;            //FTP Login name 
        public string ftpPassword;          //FTP password 
        public string Ipath;                // Target file storage path 
        public string ftpURI;               // Got FTPUrL
        public string ftpUrls;              // Get relative Url

        #region FTP initialization 
        /// <summary>
        ///  obtain FTP Of URL
        /// </summary>
        /// <param name="ftpServerIP"></param>
        /// <param name="ftpServerPort"></param>
        /// <param name="ftpRemotePath"></param>
        /// <param name="ftpUserID"></param>
        /// <param name="ftpPassword"></param>
        /// <param name="Ipath"></param>
        public string getFtpHelper(string ftpServerIP, string ftpServerPort, string ftpRemotePath, string ftpUserID, string ftpPassword, string Ipath)
        {
    
            this.ftpServerIP = ftpServerIP;
            this.ftpRemotePath = ftpRemotePath;
            this.ftpServerPort = ftpServerPort;
            this.Ipath = Ipath;
            this.ftpUserID = ftpUserID;
            this.ftpPassword = ftpPassword;
            this.ftpUrls = "ftp://" + ftpServerIP + ":" + ftpServerPort + "/";
            this.ftpURI = "ftp://" + ftpServerIP + ":" + ftpServerPort + "/" + ftpRemotePath + "/";
            return ftpURI;
        }

        /// <summary> 
        ///  establish FTP link , Return the request object  
        /// </summary> 
        /// <param name="uri">FTP Address </param> 
        /// <param name="ftpMethod"> Operation command </param> 
        private FtpWebRequest FTPRequest(Uri uri, string ftpMethod)
        {
    
            request = (FtpWebRequest)WebRequest.Create(uri);
            request.Method = ftpMethod;
            request.UseBinary = true;
            request.KeepAlive = false;
            request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            return request;
        }

        /// <summary>
        ///  establish FTP link , Return response object 
        /// </summary>
        /// <param name="uri"> Requested URL</param>
        /// <param name="ftpMethod"> Requested method </param>
        /// <returns></returns>
        private FtpWebResponse FTPResponse(Uri uri, string ftpMethod)
        {
    
            request = (FtpWebRequest)FtpWebRequest.Create(uri);
            request.Method = ftpMethod;
            request.UseBinary = true;
            request.KeepAlive = false;                                          // Keep connected , Other ways to close 
            request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            return (FtpWebResponse)request.GetResponse();
        }

        /// <summary> 
        ///  The destructor closes the connection , If you don't parse the constructor , You can go online to find C# Destructor  
        /// </summary> 
        ~FtpHelper()
        {
    
            if (response != null)
            {
    
                response.Close();
                response = null;
            }
            if (request != null)
            {
    
                request.Abort();
                request = null;
            }
        }
        #endregion


        #region  Create directory 
        /// <summary>
        ///  Create directory 
        /// </summary>
        /// <param name="remoteDirectoryName"> Directory name </param>
        public OperationResult CreateDirectory(string remoteDirectoryName)
        {
    
            bool flag=IsExist(remoteDirectoryName);
            if (!flag)
            {
    
                try
                {
    
                    response = FTPResponse(new Uri(ftpUrls + ftpRemotePath + "/"  + remoteDirectoryName), WebRequestMethods.Ftp.MakeDirectory);
                    operationResult.isOk = true;
                    operationResult.tRes = string.Format(" Create directory {0} success ", remoteDirectoryName);
                }
                catch (Exception ex)
                {
    
                    operationResult.isOk = false;
                    operationResult.tRes = string.Format(" Failed to create directory , Reasons for failure :{0}", ex.ToString());
                }
            }
            else 
            {
    
                operationResult.isOk = true;
                operationResult.tRes = string.Format(" Catalog {0} Already exists ", remoteDirectoryName);
            }
            return operationResult;
        }
        #endregion


        #region  Change directory or file name 
        /// <summary>
        ///  Change directory or file name 
        /// </summary>
        /// <param name="currentName"> Current directory or file name </param>
        /// <param name="newName"> New directory or file name after modification </param>
        public OperationResult ReName(string currentName, string newName)
        {
    
            try
            {
    
                request = FTPRequest(new Uri(ftpURI + currentName), WebRequestMethods.Ftp.Rename);
                request.RenameTo = newName;
                response = (FtpWebResponse)request.GetResponse();
                operationResult.isOk = true;
                operationResult.tRes = " Changing directory or file name succeeded ";
            }
            catch (Exception ex)
            {
    
                operationResult.isOk = false;
                operationResult.tRes = string.Format(" Failed to change directory or file name , Reasons for failure :{0}", ex.ToString());
            }
            return operationResult;
        }
        #endregion


        #region  Switch the current directory 
        /// <summary> 
        ///  Switch the current directory  
        /// </summary> 
        /// <param name="IsRoot">true: Absolute path  false: Relative paths </param> 
        public void GotoDirectory(string DirectoryName, bool IsRoot)
        {
    
            if (IsRoot)
            {
    
                ftpRemotePath = DirectoryName;
            }
            else
            {
    
                ftpRemotePath += "/" + DirectoryName;
            }
            ftpURI = "ftp://" + ftpServerIP + ":" + ftpServerPort + "/" + ftpRemotePath + "/";
        }
        #endregion


        #region  List all files in the current directory 
        /// <summary>
        ///  List all files in the current directory 
        /// </summary>
        /// <param name="remoteDirectoryName"> Directory name </param>
        /// <param name="IsDir"> Whether to include subdirectories </param>
        /// <returns></returns>
        public List<FileStruct> ListFiles(string remoteDirectoryName, bool IsDir)
        {
    
            var listAll = getAllFilesAndDirectories(remoteDirectoryName, IsDir);
            var listFile = listAll.Where(m => m.IsDirectory == false).ToList();
            return listFile;
        }
        #endregion


        #region  List all first level subdirectories of the current directory 
        /// <summary> 
        ///  List all first level subdirectories of the current directory  
        /// </summary> 
        public List<FileStruct> ListDirectories()
        {
    
            var listAll = ListFilesAndDirectories();
            var listFile = listAll.Where(m => m.IsDirectory == true).ToList();
            return listFile;
        }
        #endregion


        #region  Judge whether the specified subdirectory or file in the current directory exists 
        /// <summary> 
        ///  Judge whether the specified subdirectory or file in the current directory exists  
        /// </summary> 
        /// <param name="remoteDirName"> Specified directory or file name </param> 
        public bool IsExist(string remoteDirName)
        {
    
            var list = ListFilesAndDirectories();
            if (list.Count(m => m.Name == remoteDirName) > 0)
            {
    
                return true;
            }
            return false;
        }
        #endregion


        #region  Judge whether the specified sub file in the current directory exists 
        /// <summary>
        ///  Judge whether the specified sub file in the current directory exists 
        /// </summary>
        /// <param name="remoteDirectoryName"> Directory name </param>
        /// <param name="IsDir"> Whether to include subfolders </param>
        /// <param name="remoteFileName"> Remote filename </param>
        /// <returns></returns>
        public bool IsFileExist(string remoteDirectoryName, bool IsDir, string remoteFileName)
        {
    
            var listFile = ListFiles(remoteDirectoryName, IsDir);
            if (listFile.Count(m => m.Name == remoteFileName) > 0)
            {
    
                return true;
            }
            return false;
        } 
        #endregion


        #region  Delete empty directory 
        /// <summary>
        ///  Delete empty directory 
        /// </summary>
        /// <param name="remoteDirectoryName"> Directory relative path </param>
        public OperationResult RemoveNullDirectory(string remoteDirectoryName)
        {
    
            try
            {
    
                GotoDirectory(remoteDirectoryName, false);
                response = FTPResponse(new Uri(ftpURI), WebRequestMethods.Ftp.RemoveDirectory);
                operationResult.isOk = true;
                operationResult.tRes = " Delete empty directory succeeded ";
            }
            catch (Exception ex)
            {
    
                operationResult.isOk = false;
                operationResult.tRes = string.Format(" Failed to delete empty directory successfully , Reasons for failure :{0}", ex.ToString());
            }
            return operationResult;
        }
        #endregion


        #region  Delete directory ( Include all subdirectories and sub files below )
        /// <summary>
        ///  Delete directory ( Include all subdirectories and sub files below )
        /// </summary>
        /// <param name="remoteDirectoryName"> Directory absolute path </param>
        /// <param name="IsDir"> Delete subdirectory </param>
        public OperationResult RemoveDirectory(string remoteDirectoryName,bool IsDir)
        {
    
            fileLists = new List<FileStruct>();
            try
            {
    
                var listAll = getAllFilesAndDirectories(remoteDirectoryName,IsDir);
                if (listAll.Count > 0) 
                {
    
                    foreach (var m in listAll)
                    {
    
                        if (!m.IsDirectory)
                        {
    
                            DeleteFile(m.Path);
                        }
                        else  // Then delete the subdirectory 
                        {
    
                            GotoDirectory(m.Path, true);
                            response = FTPResponse(new Uri(ftpURI), WebRequestMethods.Ftp.RemoveDirectory);
                        }
                    }
                }
                if (IsDir) 
                {
    
                    GotoDirectory(remoteDirectoryName, true);
                    response = FTPResponse(new Uri(ftpURI), WebRequestMethods.Ftp.RemoveDirectory);
                }
                operationResult.isOk = true;
                operationResult.tRes = String.Format(" Delete directory {0} success ", remoteDirectoryName);
            }
            catch (Exception ex)
            {
    
                operationResult.isOk = false;
                operationResult.tRes = string.Format(" Delete directory {0} Success, failure , Reasons for failure :{1}", remoteDirectoryName, ex.ToString());
            }
            return operationResult;
        }
        #endregion


        #region  Delete file 
        /// <summary> 
        ///  Delete file  
        /// </summary> 
        /// <param name="remoteFileName"> Filename to delete ,FTP+ Relative paths </param>
        public void DeleteFile(string remoteFileName)
        {
    
            response = FTPResponse(new Uri(ftpUrls+ remoteFileName), WebRequestMethods.Ftp.DeleteFile);
        }
        #endregion


        #region  Download a single file 
        /// <summary>
        ///  Download a single file 
        /// </summary>
        /// <param name="saveFilePath"> Save path after downloading </param>
        /// <param name="downloadFileName"> file name , Relative paths </param>
        /// <param name="IsCreateIpath"> Do you want to create a directory </param>
        public void DownloadSingleFile(string saveFilePath, string downloadFileName, bool IsCreateIpath)
        {
    
            if (IsCreateIpath)
            {
    
                saveFilePath += "\\" + downloadFileName;
                // Determine whether the directory exists , Create a directory if it doesn't exist 
                filesHelper.CreateDirectory(System.IO.Path.GetDirectoryName(saveFilePath));
            }
            else 
            {
    
                saveFilePath += "\\" + System.IO.Path.GetFileName(downloadFileName);
            }
            using (FileStream outputStream = new FileStream(saveFilePath, FileMode.Create))
            {
    
                response = FTPResponse(new Uri(ftpUrls + downloadFileName), WebRequestMethods.Ftp.DownloadFile);
                using (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);
                    }
                }
            }  
        }
        #endregion


        #region  Batch download all files and directories in the current directory 
        /// <summary>
        ///  Batch download all files and directories in the current directory 
        /// </summary>
        /// <param name="saveFilePath"> Save path after downloading </param>
        /// <param name="remoteDirectoryName"> Directory to download </param>
        /// <param name="IsDir"> Whether to include subdirectories </param>
        /// <param name="IsCreateIpath"> Whether to create a subdirectory </param>
        public Tuple<OperationResult, List<FileStruct>> DownloadAllFile(string saveFilePath, string remoteDirectoryName, bool IsDir,bool IsCreateIpath)
        {
    
            fileLists = new List<FileStruct>();
            try
            {
    
                var listAll = getAllFilesAndDirectories(remoteDirectoryName,IsDir);
                if (listAll.Count > 0)
                {
    
                    foreach (var m in listAll)
                    {
    
                        if (!m.IsDirectory)
                        {
    
                            DownloadSingleFile(saveFilePath, m.Path, IsCreateIpath);
                        }
                    }
                }
                operationResult.isOk = true;
                operationResult.tRes = String.Format(" Download the current directory {0} All the files under are successfully ", remoteDirectoryName);
            }
            catch (Exception ex)
            {
    
                operationResult.isOk = false;
                operationResult.tRes = string.Format(" Download the current directory {0} All files under succeeded or failed , Reasons for failure :{1}", remoteDirectoryName, ex.ToString());
            }
            return new Tuple<OperationResult,List<FileStruct>>(operationResult, fileLists);
        }
        #endregion


        #region  Single file upload 
        /// <summary>
        ///  Single file upload 
        /// </summary>
        /// <param name="localFilePath"> Local absolute path </param>
        /// <param name="IsCreateIpath"> Whether to create a directory </param>
        public void UploadSingleFile(string localFilePath,Uri ftpURI)
        {
    
            FileInfo fileInfo = new FileInfo(localFilePath);
            request = FTPRequest(new Uri(ftpURI + fileInfo.Name), WebRequestMethods.Ftp.UploadFile);
            request.ContentLength = fileInfo.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            using (var fs = fileInfo.OpenRead())
            {
    
                using (var strm = request.GetRequestStream())
                {
    
                    contentLen = fs.Read(buff, 0, buffLength);
                    while (contentLen != 0)
                    {
    
                        strm.Write(buff, 0, contentLen);
                        contentLen = fs.Read(buff, 0, buffLength);
                    }
                }
            }
        }
        #endregion


        #region  Batch upload all files in the current directory 
        /// <summary>
        ///  Batch upload all files in the current directory 
        /// </summary>
        /// <param name="Ipath">Windows Absolute path </param>
        /// <param name="IsDir"> Whether to include subdirectories </param>
        /// <param name="IsCreateIpath"> Whether in Ftp Create subdirectories on </param>
        /// <returns></returns>
        public OperationResult UploadAllFile(string Ipath,bool IsDir,bool IsCreateIpath)
        {
    
            try
            {
    
                var data = filesHelper.GetDirectoryAndFile(Ipath, IsDir);
                if (data.Item1.isOk)
                {
    
                    foreach (var item in data.Item3.Values)
                    {
    
                        if (IsCreateIpath)
                        {
    
                            string fileRelationPath = System.IO.Path.GetDirectoryName(item).Substring(3).Replace("\\","/");
                            var data1 = CreateDirectory(fileRelationPath);
                            if (data1.isOk)
                            {
    
                                ftpURI = ftpUrls+ ftpRemotePath + "/" + fileRelationPath + "/";
                            }
                        }
                        UploadSingleFile(item, new Uri(ftpURI));
                    }
                }
                operationResult.isOk = true;
                operationResult.tRes = string.Format(" Batch upload current directory {0} All the files under are successfully ", Ipath);
            }
            catch (Exception ex) 
            {
    
                operationResult.isOk = false;
                operationResult.tRes = string.Format(" Batch upload current directory {0} All files under failed , Reasons for failure {1}", Ipath,ex.ToString());
            }
            return operationResult;
        } 
        #endregion


        #region  Recursive get FTP Directory and file information on the server 
        /// <summary>
        ///  Recursive get FTP Directory and file information on the server 
        /// </summary>
        /// <param name="remoteDirectoryName"> Directory absolute path </param>
        /// <param name="IsDir"> Whether to get the files in the subdirectory </param>
        public List<FileStruct> getAllFilesAndDirectories(string remoteDirectoryName,bool IsDir)
        {
    
            try
            {
    
                GetListFilesAndDirectories(remoteDirectoryName,IsDir);
            }
            catch (Exception ex) 
            {
    
                return null;
            }
            return fileLists;
        }

        /// <summary>
        ///  Get the files and folders in the current directory 
        /// </summary>
        /// <param name="remoteDirectoryName"> Directory absolute path </param>
        /// <param name="IsDir"> Whether to get the files in the subfolder </param>
        public void GetListFilesAndDirectories(string remoteDirectoryName,bool IsDir)
        {
    
            GotoDirectory(remoteDirectoryName, true);
            var listAll = ListFilesAndDirectories();
            foreach (var m in listAll)
            {
    
                if (m.IsDirectory)
                {
    
                    if (IsDir)  // Get subfolders 
                    {
    
                        GetListFilesAndDirectories(m.Path,true);
                    } 
                }
                fileLists.Add(m);
            }
        } 
        #endregion


        #region  Get the first level subdirectory and file information of the current directory 
        /// <summary>
        ///  Get the first level word directory and file information of the current directory 
        /// </summary>
        /// <param name="IsOnlyDir"> Get directory only </param>
        /// <returns></returns>
        public List<FileStruct> ListFilesAndDirectories()
        {
    
            var fileList = new List<FileStruct>();
            response = FTPResponse(new Uri(ftpURI), WebRequestMethods.Ftp.ListDirectoryDetails);   
            using (var stream = response.GetResponseStream())
            {
    
                using (var sr = new StreamReader(stream))
                {
    
                    string line = null;
                    while ((line = sr.ReadLine()) != null)
                    {
    
                        DateTime dtDate = DateTime.ParseExact(line.Substring(0, 8), "MM-dd-yy", null);
                        DateTime dtDateTime = DateTime.Parse(dtDate.ToString("yyyy-MM-dd") + line.Substring(8, 9));
                        string[] arrs = line.Split(' ');
                        var model = new FileStruct()
                        {
    
                            IsDirectory = line.IndexOf("<DIR>") > 0 ? true : false,
                            CreateTime = dtDateTime,
                            Name = arrs[arrs.Length - 1],
                            Path = ftpRemotePath + "/" + arrs[arrs.Length - 1]
                        };
                        fileList.Add(model);
                    }
                }
            }
            return fileList;
        }
        #endregion
    }

版权声明
本文为[Plant a sweet smell]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/110/202204200619556766.html