好久不見,我又回來了。 給大家分享一個我最近使用c#代碼操作ftp伺服器的代碼示例: 1 public abstract class FtpOperation 2 { 3 /// <summary> 4 /// FTP伺服器地址 5 /// </summary> 6 private string f ...
好久不見,我又回來了。
給大家分享一個我最近使用c#代碼操作ftp伺服器的代碼示例:
1 public abstract class FtpOperation 2 { 3 /// <summary> 4 /// FTP伺服器地址 5 /// </summary> 6 private string ftpServer; 7 8 /// <summary> 9 /// 用戶名 10 /// </summary> 11 private string userName; 12 13 /// <summary> 14 /// 密碼 15 /// </summary> 16 private string passWord; 17 18 /// <summary> 19 /// FTPHelper類的構造函數 20 /// </summary> 21 /// <param name="ftpServer">FTP伺服器地址</param> 22 /// <param name="userName">用戶名</param> 23 /// <param name="passWord">密碼</param> 24 public FtpOperation(string ftpServer, string userName, string passWord) 25 { 26 this.ftpServer = ftpServer; 27 this.userName = userName; 28 this.passWord = passWord; 29 } 30 31 /// <summary> 32 /// 執行FTP操作的方法 33 /// </summary> 34 /// <param name="action">要執行的操作</param> 35 private void ExecuteFtpOperation(Action action) 36 { 37 try 38 { 39 action.Invoke(); 40 } 41 catch (WebException ex) 42 { 43 if (ex.Status == WebExceptionStatus.Timeout) 44 { 45 Console.WriteLine("連接超時。"); 46 } 47 else 48 { 49 Console.WriteLine("發生錯誤 WebException: {0}", ex.Message); 50 } 51 } 52 catch (Exception ex) 53 { 54 Console.WriteLine("發生錯誤: {0}", ex.Message); 55 } 56 } 57 } 58 }基礎類的構造函數和屬性
1 /// <summary> 2 /// 執行FTP操作的方法 3 /// </summary> 4 /// <param name="action">要執行的操作</param> 5 private void ExecuteFtpOperation(Action action) 6 { 7 try 8 { 9 action.Invoke(); 10 } 11 catch (WebException ex) 12 { 13 if (ex.Status == WebExceptionStatus.Timeout) 14 { 15 Console.WriteLine("連接超時。"); 16 } 17 else 18 { 19 Console.WriteLine("發生錯誤 WebException: {0}", ex.Message); 20 } 21 } 22 catch (Exception ex) 23 { 24 Console.WriteLine("發生錯誤: {0}", ex.Message); 25 } 26 } 27 28 #region 文件查詢 29 30 /// <summary> 31 /// 遞歸查詢FTP伺服器上所有文件和目錄 32 /// </summary> 33 /// <param name="ftpDirectoryPath">要查詢的目錄路徑</param> 34 public virtual List<FileInfo> RecursiveQueryAll(string ftpDirectoryPath = "") 35 { 36 List<FileInfo> list = new List<FileInfo>(); 37 ExecuteFtpOperation(() => 38 { 39 List<FileInfo> currentList = QueryAll(ftpDirectoryPath); 40 list.AddRange(currentList); 41 42 foreach (var fileInfo in currentList) 43 { 44 if (fileInfo.FileType == "Folder") 45 { 46 // 如果是文件夾,遞歸查詢 47 List<FileInfo> subList = RecursiveQueryAll(ftpDirectoryPath + "/" + fileInfo.FileName); 48 list.AddRange(subList); 49 } 50 } 51 }); 52 return list; 53 } 54 55 /// <summary> 56 /// 查詢FTP伺服器上所有文件和目錄 57 /// </summary> 58 /// <param name="ftpDirectoryPath">要查詢的目錄路徑</param> 59 public virtual List<FileInfo> QueryAll(string ftpDirectoryPath = "") 60 { 61 List<FileInfo> list = new List<FileInfo>(); 62 ExecuteFtpOperation(() => 63 { 64 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + ftpDirectoryPath); 65 request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 66 request.Credentials = new NetworkCredential(userName, passWord); 67 request.Timeout = 5000; 68 69 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 70 { 71 //Console.WriteLine("狀態: {0}", response.StatusDescription); 72 73 using (var responseStream = response.GetResponseStream()) 74 { 75 if (responseStream != null) 76 { 77 using (var reader = new StreamReader(responseStream)) 78 { 79 string line = reader.ReadLine(); 80 while (!string.IsNullOrEmpty(line)) 81 { 82 list.AddRange(ParseFTPFileList(line)); 83 line = reader.ReadLine(); 84 } 85 } 86 } 87 } 88 } 89 }); 90 return list; 91 } 92 93 /// <summary> 94 /// 解析FTP伺服器返回的文件列表信息,將其轉換為FileInfo對象列表 95 /// </summary> 96 /// <param name="ftpFileList">FTP伺服器返回的文件列表信息</param> 97 /// <returns>包含文件信息的FileInfo對象列表</returns> 98 public virtual List<FileInfo> ParseFTPFileList(string ftpFileList) 99 { 100 // 解析FTP返回的文件列表信息並返回FileInfo對象列表 101 List<FileInfo> filesInfo = new List<FileInfo>(); 102 103 // 按行分割FTP文件列表信息 104 string[] lines = ftpFileList.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); 105 106 foreach (string line in lines) 107 { 108 // 按空格分割行信息 109 string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 110 111 if (parts.Length >= 4) 112 { 113 114 string lastModifiedDateStr = parts[0] + " " + parts[1]; 115 string format = "MM-dd-yy hh:mmtt"; // 指定日期時間的確切格式 116 DateTime lastModifiedDate; 117 DateTime.TryParseExact(lastModifiedDateStr, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out lastModifiedDate); 118 119 // 提取文件大小信息 120 string fileSizeStr = parts[2]; 121 long fileSize; 122 string fileType = "Folder"; 123 string fileName = string.Join(" ", parts, 3, parts.Length - 3); 124 if (fileSizeStr.Contains("DIR")) 125 { 126 127 fileSize = 0; 128 } 129 else 130 { 131 fileType = Path.GetExtension(fileName); 132 fileSize = Convert.ToInt64(fileSizeStr); 133 } 134 135 136 FileInfo fileInfo = new FileInfo(lastModifiedDate, fileSize, fileType, fileName); 137 138 filesInfo.Add(fileInfo); 139 } 140 } 141 142 return filesInfo; 143 } 144 #endregion 145 146 #region 判斷FTP伺服器上是否存在指定文件夾 && 在FTP伺服器上創建文件夾 &&刪除FTP伺服器上的空文件夾 147 /// <summary> 148 /// 判斷FTP伺服器上是否存在指定文件夾 149 /// </summary> 150 /// <param name="directoryPath">要檢查的文件夾路徑</param> 151 /// <returns>文件夾是否存在的布爾值</returns> 152 public virtual bool FtpDirectoryExists(string directoryPath) 153 { 154 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + directoryPath); 155 request.Credentials = new NetworkCredential(userName, passWord); 156 request.Method = WebRequestMethods.Ftp.ListDirectory; 157 158 try 159 { 160 FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 161 response.Close(); 162 return true; 163 } 164 catch (WebException ex) 165 { 166 FtpWebResponse response = (FtpWebResponse)ex.Response; 167 if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) 168 { 169 return false; 170 } 171 throw; 172 } 173 } 174 175 /// <summary> 176 /// 在FTP伺服器上創建文件夾 177 /// </summary> 178 /// <param name="folderName">要創建的文件夾名稱</param> 179 public virtual void FtpCreateDirectory(string folderName) 180 { 181 ExecuteFtpOperation(() => 182 { 183 string[] pathArray = folderName.Split('/'); 184 var tempPath = ""; 185 foreach (var path in pathArray) 186 { 187 if (path == "") 188 { 189 continue; 190 } 191 tempPath += path + "/"; 192 if (FtpDirectoryExists(tempPath)) 193 { 194 continue; 195 } 196 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + tempPath); 197 request.Method = WebRequestMethods.Ftp.MakeDirectory; 198 request.Credentials = new NetworkCredential(userName, passWord); 199 200 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 201 { 202 Console.WriteLine($"文件夾{path}創建成功。"); 203 } 204 } 205 206 }); 207 } 208 /// <summary> 209 /// 刪除FTP伺服器上的空文件夾 210 /// </summary> 211 /// <param name="ftpFolderPath">FTP伺服器上的空文件夾路徑</param> 212 public virtual void FtpDeleteFolder(string ftpFolderPath) 213 { 214 ExecuteFtpOperation(() => 215 { 216 if (string.IsNullOrEmpty(ftpFolderPath)) 217 { 218 return; 219 } 220 // 連接到 FTP 伺服器 221 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + ftpFolderPath); 222 request.Credentials = new NetworkCredential(userName, passWord); 223 request.Method = WebRequestMethods.Ftp.RemoveDirectory; 224 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 225 { 226 Console.WriteLine($"文件夾{new DirectoryInfo(ftpFolderPath).Name}刪除成功!"); 227 } 228 }); 229 } 230 #endregion 231 232 #region 文件、文件夾刪除 233 /// <summary> 234 /// 刪除FTP伺服器指定路徑下的多個文件 235 /// </summary> 236 /// <param name="directoryPath">要刪除文件的目錄路徑</param> 237 /// <param name="fileNames">要刪除的文件名數組</param> 238 public virtual void FtpDeleteFiles(string directoryPath, string[] fileNames) 239 { 240 ExecuteFtpOperation(() => 241 { 242 foreach (var fileName in fileNames) 243 { 244 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + directoryPath + "/" + fileName); 245 request.Method = WebRequestMethods.Ftp.DeleteFile; 246 request.Credentials = new NetworkCredential(userName, passWord); 247 248 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 249 { 250 Console.WriteLine($"文件 '{fileName}' 刪除成功。"); 251 } 252 } 253 }); 254 } 255 256 /// <summary> 257 /// 遞歸刪除FTP伺服器上的文件夾及其內容 258 /// </summary> 259 /// <param name="directoryPath">要刪除的文件夾路徑</param> 260 public virtual void FtpDeleteFolders(string directoryPath) 261 { 262 ExecuteFtpOperation(() => 263 { 264 265 if (!FtpDirectoryExists(directoryPath)) 266 { 267 Console.WriteLine($"{directoryPath} 不存在!"); 268 return; 269 } 270 271 // 獲取文件夾內所有文件和子文件夾 272 var fileList = QueryAll(directoryPath); 273 foreach (var fileInfo in fileList) 274 { 275 // 刪除文件 276 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + directoryPath + "/" + fileInfo.FileName); 277 request.Method = WebRequestMethods.Ftp.DeleteFile; 278 request.Credentials = new NetworkCredential(userName, passWord); 279 280 // 如果是文件夾,遞歸刪除 281 if (fileInfo.FileType == "Folder") 282 { 283 FtpDeleteFolders(directoryPath + "/" + fileInfo.FileName); 284 } 285 else 286 { 287 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 288 { 289 Console.WriteLine($"文件 '{fileInfo.FileName}' 刪除成功。"); 290 } 291 } 292 293 294 295 } 296 297 // 刪除空文件夾 298 FtpDeleteFolder(directoryPath); 299 }); 300 } 301 302 303 #endregion 304 305 #region 文件移動 306 307 /// <summary> 308 /// 移動FTP伺服器上的多個文件 309 /// </summary> 310 /// <param name="sourceDirectoryPath">