c# 代碼操作ftp服務(wù)器文件
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
給大家分享一個(gè)我最近使用c#代碼操作ftp服務(wù)器的代碼示例: 基礎(chǔ)類的構(gòu)造函數(shù)和屬性 public abstract class FtpOperation { /// <summary> /// FTP服務(wù)器地址 /// </summary> private string ftpServer;
/// <summary> /// 用戶名 /// </summary> private string userName;
/// <summary> /// 密碼 /// </summary> private string passWord;
/// <summary> /// FTPHelper類的構(gòu)造函數(shù) /// </summary> /// <param name="ftpServer">FTP服務(wù)器地址</param> /// <param name="userName">用戶名</param> /// <param name="passWord">密碼</param> public FtpOperation(string ftpServer, string userName, string passWord) { this.ftpServer = ftpServer; this.userName = userName; this.passWord = passWord; }
/// <summary> /// 執(zhí)行FTP操作的方法 /// </summary> /// <param name="action">要執(zhí)行的操作</param> private void ExecuteFtpOperation(Action action) { try { action.Invoke(); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.Timeout) { Console.WriteLine("連接超時(shí)。"); } else { Console.WriteLine("發(fā)生錯(cuò)誤 WebException: {0}", ex.Message); } } catch (Exception ex) { Console.WriteLine("發(fā)生錯(cuò)誤: {0}", ex.Message); } } } } /// <summary> /// 執(zhí)行FTP操作的方法 /// </summary> /// <param name="action">要執(zhí)行的操作</param> private void ExecuteFtpOperation(Action action) { try { action.Invoke(); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.Timeout) { Console.WriteLine("連接超時(shí)。"); } else { Console.WriteLine("發(fā)生錯(cuò)誤 WebException: {0}", ex.Message); } } catch (Exception ex) { Console.WriteLine("發(fā)生錯(cuò)誤: {0}", ex.Message); } } #region 文件查詢 /// <summary> /// 遞歸查詢FTP服務(wù)器上所有文件和目錄 /// </summary> /// <param name="ftpDirectoryPath">要查詢的目錄路徑</param> public virtual List<FileInfo> RecursiveQueryAll(string ftpDirectoryPath = "") { List<FileInfo> list = new List<FileInfo>(); ExecuteFtpOperation(() => { List<FileInfo> currentList = QueryAll(ftpDirectoryPath); list.AddRange(currentList); foreach (var fileInfo in currentList) { if (fileInfo.FileType == "Folder") { // 如果是文件夾,遞歸查詢 List<FileInfo> subList = RecursiveQueryAll(ftpDirectoryPath + "/" + fileInfo.FileName); list.AddRange(subList); } } }); return list; } /// <summary> /// 查詢FTP服務(wù)器上所有文件和目錄 /// </summary> /// <param name="ftpDirectoryPath">要查詢的目錄路徑</param> public virtual List<FileInfo> QueryAll(string ftpDirectoryPath = "") { List<FileInfo> list = new List<FileInfo>(); ExecuteFtpOperation(() => { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + ftpDirectoryPath); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; request.Credentials = new NetworkCredential(userName, passWord); request.Timeout = 5000; using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { //Console.WriteLine("狀態(tài): {0}", response.StatusDescription); using (var responseStream = response.GetResponseStream()) { if (responseStream != null) { using (var reader = new StreamReader(responseStream)) { string line = reader.ReadLine(); while (!string.IsNullOrEmpty(line)) { list.AddRange(ParseFTPFileList(line)); line = reader.ReadLine(); } } } } } }); return list; } /// <summary> /// 解析FTP服務(wù)器返回的文件列表信息,將其轉(zhuǎn)換為FileInfo對(duì)象列表 /// </summary> /// <param name="ftpFileList">FTP服務(wù)器返回的文件列表信息</param> /// <returns>包含文件信息的FileInfo對(duì)象列表</returns> public virtual List<FileInfo> ParseFTPFileList(string ftpFileList) { // 解析FTP返回的文件列表信息并返回FileInfo對(duì)象列表 List<FileInfo> filesInfo = new List<FileInfo>(); // 按行分割FTP文件列表信息 string[] lines = ftpFileList.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { // 按空格分割行信息 string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length >= 4) { string lastModifiedDateStr = parts[0] + " " + parts[1]; string format = "MM-dd-yy hh:mmtt"; // 指定日期時(shí)間的確切格式 DateTime lastModifiedDate; DateTime.TryParseExact(lastModifiedDateStr, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out lastModifiedDate); // 提取文件大小信息 string fileSizeStr = parts[2]; long fileSize; string fileType = "Folder"; string fileName = string.Join(" ", parts, 3, parts.Length - 3); if (fileSizeStr.Contains("DIR")) { fileSize = 0; } else { fileType = Path.GetExtension(fileName); fileSize = Convert.ToInt64(fileSizeStr); } FileInfo fileInfo = new FileInfo(lastModifiedDate, fileSize, fileType, fileName); filesInfo.Add(fileInfo); } } return filesInfo; } #endregion #region 判斷FTP服務(wù)器上是否存在指定文件夾 && 在FTP服務(wù)器上創(chuàng)建文件夾 &&刪除FTP服務(wù)器上的空文件夾 /// <summary> /// 判斷FTP服務(wù)器上是否存在指定文件夾 /// </summary> /// <param name="directoryPath">要檢查的文件夾路徑</param> /// <returns>文件夾是否存在的布爾值</returns> public virtual bool FtpDirectoryExists(string directoryPath) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + directoryPath); request.Credentials = new NetworkCredential(userName, passWord); request.Method = WebRequestMethods.Ftp.ListDirectory; try { FtpWebResponse response = (FtpWebResponse)request.GetResponse(); response.Close(); return true; } catch (WebException ex) { FtpWebResponse response = (FtpWebResponse)ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { return false; } throw; } } /// <summary> /// 在FTP服務(wù)器上創(chuàng)建文件夾 /// </summary> /// <param name="folderName">要?jiǎng)?chuàng)建的文件夾名稱</param> public virtual void FtpCreateDirectory(string folderName) { ExecuteFtpOperation(() => { string[] pathArray = folderName.Split('/'); var tempPath = ""; foreach (var path in pathArray) { if (path == "") { continue; } tempPath += path + "/"; if (FtpDirectoryExists(tempPath)) { continue; } FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + tempPath); request.Method = WebRequestMethods.Ftp.MakeDirectory; request.Credentials = new NetworkCredential(userName, passWord); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Console.WriteLine($"文件夾{path}創(chuàng)建成功。"); } } }); } /// <summary> /// 刪除FTP服務(wù)器上的空文件夾 /// </summary> /// <param name="ftpFolderPath">FTP服務(wù)器上的空文件夾路徑</param> public virtual void FtpDeleteFolder(string ftpFolderPath) { ExecuteFtpOperation(() => { if (string.IsNullOrEmpty(ftpFolderPath)) { return; } // 連接到 FTP 服務(wù)器 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + ftpFolderPath); request.Credentials = new NetworkCredential(userName, passWord); request.Method = WebRequestMethods.Ftp.RemoveDirectory; using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Console.WriteLine($"文件夾{new DirectoryInfo(ftpFolderPath).Name}刪除成功!"); } }); } #endregion #region 文件、文件夾刪除 /// <summary> /// 刪除FTP服務(wù)器指定路徑下的多個(gè)文件 /// </summary> /// <param name="directoryPath">要?jiǎng)h除文件的目錄路徑</param> /// <param name="fileNames">要?jiǎng)h除的文件名數(shù)組</param> public virtual void FtpDeleteFiles(string directoryPath, string[] fileNames) { ExecuteFtpOperation(() => { foreach (var fileName in fileNames) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + directoryPath + "/" + fileName); request.Method = WebRequestMethods.Ftp.DeleteFile; request.Credentials = new NetworkCredential(userName, passWord); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Console.WriteLine($"文件 '{fileName}' 刪除成功。"); } } }); } /// <summary> /// 遞歸刪除FTP服務(wù)器上的文件夾及其內(nèi)容 /// </summary> /// <param name="directoryPath">要?jiǎng)h除的文件夾路徑</param> public virtual void FtpDeleteFolders(string directoryPath) { ExecuteFtpOperation(() => { if (!FtpDirectoryExists(directoryPath)) { Console.WriteLine($"{directoryPath} 不存在!"); return; } // 獲取文件夾內(nèi)所有文件和子文件夾 var fileList = QueryAll(directoryPath); foreach (var fileInfo in fileList) { // 刪除文件 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + directoryPath + "/" + fileInfo.FileName); request.Method = WebRequestMethods.Ftp.DeleteFile; request.Credentials = new NetworkCredential(userName, passWord); // 如果是文件夾,遞歸刪除 if (fileInfo.FileType == "Folder") { FtpDeleteFolders(directoryPath + "/" + fileInfo.FileName); } else { using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Console.WriteLine($"文件 '{fileInfo.FileName}' 刪除成功。"); } } } // 刪除空文件夾 FtpDeleteFolder(directoryPath); }); } #endregion #region 文件移動(dòng) /// <summary> /// 移動(dòng)FTP服務(wù)器上的多個(gè)文件 /// </summary> /// <param name="sourceDirectoryPath">源文件目錄路徑</param> /// <param name="destinationDirectoryPath">目標(biāo)文件目錄路徑</param> /// <param name="fileNames">要移動(dòng)的文件名數(shù)組</param> public virtual void FtpMoveFiles(string sourceDirectoryPath, string destinationDirectoryPath, string[] fileNames) { ExecuteFtpOperation(() => { if (!FtpDirectoryExists(sourceDirectoryPath)) { Console.WriteLine($"{sourceDirectoryPath} 目錄不存在!"); return; } if (!FtpDirectoryExists(destinationDirectoryPath)) { FtpCreateDirectory(destinationDirectoryPath); } foreach (var fileName in fileNames) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + sourceDirectoryPath + "/" + fileName); request.Method = WebRequestMethods.Ftp.Rename; request.Credentials = new NetworkCredential(userName, passWord); request.RenameTo = destinationDirectoryPath + "/" + fileName; using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Console.WriteLine($"文件 '{fileName}' 移動(dòng)成功。"); } } }); } /// <summary> /// 移動(dòng)整個(gè)文件夾到目標(biāo)位置 /// </summary> /// <param name="sourceDirectoryPath">源文件夾路徑</param> /// <param name="destinationDirectoryPath">目標(biāo)文件夾路徑</param> public virtual void FtpMoveFolder(string sourceDirectoryPath, string destinationDirectoryPath) { ExecuteFtpOperation(() => { if (!FtpDirectoryExists(sourceDirectoryPath)) { Console.WriteLine($"{sourceDirectoryPath} 目錄不存在!"); return; } //destinationDirectoryPath = destinationDirectoryPath + "/" + new DirectoryInfo(sourceDirectoryPath).Name;//解決移動(dòng)后源文件夾丟失的問(wèn)題 // 創(chuàng)建目標(biāo)文件夾 if (!FtpDirectoryExists(destinationDirectoryPath)) { FtpCreateDirectory(destinationDirectoryPath); } // 獲取源文件夾內(nèi)所有文件和子文件夾 var fileList = QueryAll(sourceDirectoryPath); foreach (var fileInfo in fileList) { // 構(gòu)建源文件和目標(biāo)文件的完整路徑 string sourcePath = sourceDirectoryPath + "/" + fileInfo.FileName; string destinationPath = destinationDirectoryPath + "/" + fileInfo.FileName; // 如果是文件夾,遞歸移動(dòng) if (fileInfo.FileType == "Folder") { FtpMoveFolder(sourcePath, destinationPath); } else { // 創(chuàng)建源文件的FTP請(qǐng)求 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + sourcePath); request.Method = WebRequestMethods.Ftp.Rename; // 使用重命名操作實(shí)現(xiàn)移動(dòng) request.Credentials = new NetworkCredential(userName, passWord); request.RenameTo = destinationPath; // 設(shè)置重命名目標(biāo)路徑 // 發(fā)起請(qǐng)求并獲取響應(yīng) using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Console.WriteLine($"文件 '{fileInfo.FileName}' 移動(dòng)成功。"); } } } if (!string.IsNullOrEmpty(sourceDirectoryPath)) { // 刪除源文件夾 FtpDeleteFolder(sourceDirectoryPath); }
}); } #endregion #region 文件上傳【文件批量上傳&&文件夾上傳】 /// <summary> /// 上傳文件到FTP服務(wù)器 /// </summary> /// <param name="filePath">要上傳的文件路徑</param> /// <param name="directoryPath">目標(biāo)文件夾路徑</param> public virtual void FtpUploadFile(string filePath, string directoryPath = "") { ExecuteFtpOperation(() => { if (!FtpDirectoryExists(directoryPath)) { FtpCreateDirectory(directoryPath); } using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential(userName, passWord); ; client.UploadFile(ftpServer + directoryPath + "/" + Path.GetFileName(filePath), WebRequestMethods.Ftp.UploadFile, filePath); Console.WriteLine($"{filePath}文件上傳成功。"); } }); } /// <summary> /// 遞歸上傳文件夾到FTP服務(wù)器 /// </summary> /// <param name="localFolderPath">本地文件夾路徑</param> /// <param name="ftpDirectoryPath">FTP服務(wù)器目標(biāo)文件夾路徑</param> public virtual void FtpUploadFolder(string localFolderPath, string ftpDirectoryPath) { // 檢查本地文件夾是否存在 if (!Directory.Exists(localFolderPath)) { Console.WriteLine("本地文件夾不存在。"); return; } // 獲取文件夾名稱 string folderName = new DirectoryInfo(localFolderPath).Name; // 構(gòu)建FTP服務(wù)器上的目標(biāo)路徑 string rootPath = (string.IsNullOrEmpty(ftpDirectoryPath) ? "" : ftpDirectoryPath + "/"); // 如果目標(biāo)文件夾在FTP服務(wù)器上不存在,則創(chuàng)建 if (!FtpDirectoryExists(rootPath + folderName)) { FtpCreateDirectory(rootPath + folderName); } // 獲取文件夾中的所有文件 string[] files = Directory.GetFiles(localFolderPath); // 逐個(gè)上傳文件 foreach (string file in files) { FtpUploadFile(file, rootPath + folderName); } // 獲取文件夾中的所有子文件夾 string[] subDirectories = Directory.GetDirectories(localFolderPath); // 逐個(gè)處理子文件夾 foreach (string subDirectory in subDirectories) { // 遞歸上傳子文件夾 FtpUploadFolder(subDirectory, rootPath + folderName); } Console.WriteLine($"{localFolderPath} 文件夾上傳成功。"); } /// <summary> /// 上傳多個(gè)文件夾到FTP服務(wù)器 /// </summary> /// <param name="filePath">要上傳的文件夾路徑</param> /// <param name="ftpDirectoryPath">目標(biāo)文件夾路徑</param> public virtual void FtpUploadFolders(string[] localDirectories, string ftpDirectoryPath = "") { foreach (string localDirectory in localDirectories) { FtpUploadFolder(localDirectory, ftpDirectoryPath); } } #endregion #region 文件下載 /// <summary> /// 從FTP服務(wù)器下載文件到本地 /// </summary> /// <param name="remoteFilePaths">要下載的遠(yuǎn)程文件路徑數(shù)組</param> /// <param name="localDirectory">本地目錄路徑</param> public virtual void FtpDownloadFile(string[] remoteFilePaths, string localDirectory) { ExecuteFtpOperation(() => { // 檢查本地路徑是否存在,如果不存在則創(chuàng)建 if (!Directory.Exists(localDirectory)) { Directory.CreateDirectory(localDirectory); } using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential(userName, passWord); foreach (var remoteFilePath in remoteFilePaths) { string fileName = remoteFilePath.Substring(remoteFilePath.LastIndexOf("/") + 1); string localFilePath = Path.Combine(localDirectory, fileName); try { client.DownloadFile(ftpServer + remoteFilePath, localFilePath); Console.WriteLine($"文件 '{fileName}' 下載成功。"); } catch (WebException ex) { Console.WriteLine($"下載文件 '{fileName}' 時(shí)出錯(cuò): {ex.Message}"); // Handle the exception as needed } } } }); } /// <summary> /// 遞歸從FTP服務(wù)器下載文件夾到本地 /// </summary> /// <param name="remoteDirectoryPath">要下載的遠(yuǎn)程文件夾路徑</param> /// <param name="localDirectory">本地目錄路徑</param> public virtual void FtpDownloadFolder(string remoteDirectoryPath, string localDirectory) { ExecuteFtpOperation(() => { // 檢查本地路徑是否存在,如果不存在則創(chuàng)建 if (!Directory.Exists(localDirectory)) { Directory.CreateDirectory(localDirectory); } // 獲取遠(yuǎn)程文件夾內(nèi)所有文件和子文件夾 var fileList = QueryAll(remoteDirectoryPath); foreach (var fileInfo in fileList) { string remotePath = remoteDirectoryPath + "/" + fileInfo.FileName; string localPath = Path.Combine(localDirectory, fileInfo.FileName); if (fileInfo.FileType == "Folder") { // 如果是文件夾,遞歸下載 string newLocalDirectory = Path.Combine(localDirectory, fileInfo.FileName); Directory.CreateDirectory(newLocalDirectory); FtpDownloadFolder(remotePath, newLocalDirectory); } else { // 如果是文件,下載到本地 using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential(userName, passWord); client.DownloadFile(ftpServer + remotePath, localPath); Console.WriteLine($"文件 '{fileInfo.FileName}' 下載成功。"); } } } }); } #endregion FtpOperation 中其他的方法 調(diào)用 // FTP 服務(wù)器地址 string ftpServer = "ftp://127.0.0.1:27/"; // FTP 服務(wù)器用戶名 string userName = "Administrator"; // FTP 服務(wù)器密碼 string password = "admin"; FtpTest ftp = new FtpTest(ftpServer, userName, password); //ftp.QueryAll("/Template"); //查詢 ftp.FtpDeleteFolders("");//刪除所有 ftp.FtpUploadFolder("e:\\CoaTemplate", "");//將文件夾的內(nèi)容上傳到根目錄 ftp.FtpUploadFolder(@"D:\GitCode\Blog.Core", "/gitCode/Blog.Core");//將本地文件夾的內(nèi)容上傳到指定目錄 var data = ftp.RecursiveQueryAll("");//查詢所有文件信息 ftp.FtpMoveFolder("/Template", "/1/Template");//文件夾移動(dòng) ftp.FtpDownloadFolder("/1", "d:\\1\\"); //將ftp服務(wù)器的指定文件夾下載到本地目錄 項(xiàng)目地址:https://github.com/yycb1994/FtpSiteManager 原文作者:我只吃飯不洗碗,轉(zhuǎn)自https://www.cnblogs.com/INetIMVC/p/18025336 該文章在 2024/2/24 15:55:24 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |