c# FTP操作类
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.IO; 5 using System.Net; 6 using System.Windows.Forms; 7 using System.Globalization; 8 9 namespace FtpLib 10 { 11 12 public class FtpWeb 13 { 14 string ftpServerIP; 15 string ftpRemotePath; 16 string ftpUserID; 17 string ftpPassword; 18 string ftpURI; 19 20 /// <summary> 21 /// 连接FTP 22 /// </summary> 23 /// <param name="FtpServerIP">FTP连接地址</param> 24 /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param> 25 /// <param name="FtpUserID">用户名</param> 26 /// <param name="FtpPassword">密码</param> 27 public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword) 28 { 29 ftpServerIP = FtpServerIP; 30 ftpRemotePath = FtpRemotePath; 31 ftpUserID = FtpUserID; 32 ftpPassword = FtpPassword; 33 ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; 34 } 35 36 /// <summary> 37 /// 上传 38 /// </summary> 39 /// <param name="filename"></param> 40 public void Upload(string filename) 41 { 42 FileInfo fileInf = new FileInfo(filename); 43 string uri = ftpURI + fileInf.Name; 44 FtpWebRequest reqFTP; 45 46 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 47 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 48 reqFTP.KeepAlive = false; 49 reqFTP.Method = WebRequestMethods.Ftp.UploadFile; 50 reqFTP.UseBinary = true; 51 reqFTP.ContentLength = fileInf.Length; 52 int buffLength = 2048; 53 byte[] buff = new byte[buffLength]; 54 int contentLen; 55 FileStream fs = fileInf.OpenRead(); 56 try 57 { 58 Stream strm = reqFTP.GetRequestStream(); 59 contentLen = fs.Read(buff, 0, buffLength); 60 while (contentLen != 0) 61 { 62 strm.Write(buff, 0, contentLen); 63 contentLen = fs.Read(buff, 0, buffLength); 64 } 65 strm.Close(); 66 fs.Close(); 67 } 68 catch (Exception ex) 69 { 70 Insert_Standard_ErrorLog.Insert("FtpWeb", "Upload Error --> " + ex.Message); 71 } 72 } 73 74 /// <summary> 75 /// 下载 76 /// </summary> 77 /// <param name="filePath"></param> 78 /// <param name="fileName"></param> 79 public void Download(string filePath, string fileName) 80 { 81 FtpWebRequest reqFTP; 82 try 83 { 84 FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create); 85 86 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName)); 87 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; 88 reqFTP.UseBinary = true; 89 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 90 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 91 Stream ftpStream = response.GetResponseStream(); 92 long cl = response.ContentLength; 93 int bufferSize = 2048; 94 int readCount; 95 byte[] buffer = new byte[bufferSize]; 96 97 readCount = ftpStream.Read(buffer, 0, bufferSize); 98 while (readCount > 0) 99 { 100 outputStream.Write(buffer, 0, readCount); 101 readCount = ftpStream.Read(buffer, 0, bufferSize); 102 } 103 104 ftpStream.Close(); 105 outputStream.Close(); 106 response.Close(); 107 } 108 catch (Exception ex) 109 { 110 Insert_Standard_ErrorLog.Insert("FtpWeb", "Download Error --> " + ex.Message); 111 } 112 } 113 114 115 /// <summary> 116 /// 删除文件 117 /// </summary> 118 /// <param name="fileName"></param> 119 public void Delete(string fileName) 120 { 121 try 122 { 123 string uri = ftpURI + fileName; 124 FtpWebRequest reqFTP; 125 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 126 127 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 128 reqFTP.KeepAlive = false; 129 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; 130 131 string result = String.Empty; 132 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 133 long size = response.ContentLength; 134 Stream datastream = response.GetResponseStream(); 135 StreamReader sr = new StreamReader(datastream); 136 result = sr.ReadToEnd(); 137 sr.Close(); 138 datastream.Close(); 139 response.Close(); 140 } 141 catch (Exception ex) 142 { 143 Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + fileName); 144 } 145 } 146 147 /// <summary> 148 /// 删除文件夹 149 /// </summary> 150 /// <param name="folderName"></param> 151 public void RemoveDirectory(string folderName) 152 { 153 try 154 { 155 string uri = ftpURI + folderName; 156 FtpWebRequest reqFTP; 157 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 158 159 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 160 reqFTP.KeepAlive = false; 161 reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory; 162 163 string result = String.Empty; 164 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 165 long size = response.ContentLength; 166 Stream datastream = response.GetResponseStream(); 167 StreamReader sr = new StreamReader(datastream); 168 result = sr.ReadToEnd(); 169 sr.Close(); 170 datastream.Close(); 171 response.Close(); 172 } 173 catch (Exception ex) 174 { 175 Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + folderName); 176 } 177 } 178 179 /// <summary> 180 /// 获取当前目录下明细(包含文件和文件夹) 181 /// </summary> 182 /// <returns></returns> 183 public string[] GetFilesDetailList() 184 { 185 string[] downloadFiles; 186 try 187 { 188 StringBuilder result = new StringBuilder(); 189 FtpWebRequest ftp; 190 ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI)); 191 ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 192 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 193 WebResponse response = ftp.GetResponse(); 194 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); 195 196 //while (reader.Read() > 0) 197 //{ 198 199 //} 200 string line = reader.ReadLine(); 201 //line = reader.ReadLine(); 202 //line = reader.ReadLine(); 203 204 while (line != null) 205 { 206 result.Append(line); 207 result.Append("\n"); 208 line = reader.ReadLine(); 209 } 210 result.Remove(result.ToString().LastIndexOf("\n"), 1); 211 reader.Close(); 212 response.Close(); 213 return result.ToString().Split('\n'); 214 } 215 catch (Exception ex) 216 { 217 downloadFiles = null; 218 Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --> " + ex.Message); 219 return downloadFiles; 220 } 221 } 222 223 /// <summary> 224 /// 获取当前目录下文件列表(仅文件) 225 /// </summary> 226 /// <returns></returns> 227 public string[] GetFileList(string mask) 228 { 229 string[] downloadFiles; 230 StringBuilder result = new StringBuilder(); 231 FtpWebRequest reqFTP; 232 try 233 { 234 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI)); 235 reqFTP.UseBinary = true; 236 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 237 reqFTP.Method = WebRequestMethods.Ftp.ListDirectory; 238 WebResponse response = reqFTP.GetResponse(); 239 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); 240 241 string line = reader.ReadLine(); 242 while (line != null) 243 { 244 if (mask.Trim() != string.Empty && mask.Trim() != "*.*") 245 { 246 247 string mask_ = mask.Substring(0, mask.IndexOf("*")); 248 if (line.Substring(0, mask_.Length) == mask_) 249 { 250 result.Append(line); 251 result.Append("\n"); 252 } 253 } 254 else 255 { 256 result.Append(line); 257 result.Append("\n"); 258 } 259 line = reader.ReadLine(); 260 } 261 result.Remove(result.ToString().LastIndexOf('\n'), 1); 262 reader.Close(); 263 response.Close(); 264 return result.ToString().Split('\n'); 265 } 266 catch (Exception ex) 267 { 268 downloadFiles = null; 269 if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。") 270 { 271 Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileList Error --> " + ex.Message.ToString()); 272 } 273 return downloadFiles; 274 } 275 } 276 277 /// <summary> 278 /// 获取当前目录下所有的文件夹列表(仅文件夹) 279 /// </summary> 280 /// <returns></returns> 281 public string[] GetDirectoryList() 282 { 283 string[] drectory = GetFilesDetailList(); 284 string m = string.Empty; 285 foreach (string str in drectory) 286 { 287 int dirPos = str.IndexOf("<DIR>"); 288 if (dirPos>0) 289 { 290 /*判断 Windows 风格*/ 291 m += str.Substring(dirPos + 5).Trim() + "\n"; 292 } 293 else if (str.Trim().Substring(0, 1).ToUpper() == "D") 294 { 295 /*判断 Unix 风格*/ 296 string dir = str.Substring(54).Trim(); 297 if (dir != "." && dir != "..") 298 { 299 m += dir + "\n"; 300 } 301 } 302 } 303 304 char[] n = new char[] { '\n' }; 305 return m.Split(n); 306 } 307 308 /// <summary> 309 /// 判断当前目录下指定的子目录是否存在 310 /// </summary> 311 /// <param name="RemoteDirectoryName">指定的目录名</param> 312 public bool DirectoryExist(string RemoteDirectoryName) 313 { 314 string[] dirList = GetDirectoryList(); 315 foreach (string str in dirList) 316 { 317 if (str.Trim() == RemoteDirectoryName.Trim()) 318 { 319 return true; 320 } 321 } 322 return false; 323 } 324 325 /// <summary> 326 /// 判断当前目录下指定的文件是否存在 327 /// </summary> 328 /// <param name="RemoteFileName">远程文件名</param> 329 public bool FileExist(string RemoteFileName) 330 { 331 string[] fileList = GetFileList("*.*"); 332 foreach (string str in fileList) 333 { 334 if (str.Trim() == RemoteFileName.Trim()) 335 { 336 return true; 337 } 338 } 339 return false; 340 } 341 342 /// <summary> 343 /// 创建文件夹 344 /// </summary> 345 /// <param name="dirName"></param> 346 public void MakeDir(string dirName) 347 { 348 FtpWebRequest reqFTP; 349 try 350 { 351 // dirName = name of the directory to create. 352 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName)); 353 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; 354 reqFTP.UseBinary = true; 355 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 356 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 357 Stream ftpStream = response.GetResponseStream(); 358 359 ftpStream.Close(); 360 response.Close(); 361 } 362 catch (Exception ex) 363 { 364 Insert_Standard_ErrorLog.Insert("FtpWeb", "MakeDir Error --> " + ex.Message); 365 } 366 } 367 368 /// <summary> 369 /// 获取指定文件大小 370 /// </summary> 371 /// <param name="filename"></param> 372 /// <returns></returns> 373 public long GetFileSize(string filename) 374 { 375 FtpWebRequest reqFTP; 376 long fileSize = 0; 377 try 378 { 379 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename)); 380 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; 381 reqFTP.UseBinary = true; 382 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 383 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 384 Stream ftpStream = response.GetResponseStream(); 385 fileSize = response.ContentLength; 386 387 ftpStream.Close(); 388 response.Close(); 389 } 390 catch (Exception ex) 391 { 392 Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileSize Error --> " + ex.Message); 393 } 394 return fileSize; 395 } 396 397 /// <summary> 398 /// 改名 399 /// </summary> 400 /// <param name="currentFilename"></param> 401 /// <param name="newFilename"></param> 402 public void ReName(string currentFilename, string newFilename) 403 { 404 FtpWebRequest reqFTP; 405 try 406 { 407 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename)); 408 reqFTP.Method = WebRequestMethods.Ftp.Rename; 409 reqFTP.RenameTo = newFilename; 410 reqFTP.UseBinary = true; 411 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 412 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 413 Stream ftpStream = response.GetResponseStream(); 414 415 ftpStream.Close(); 416 response.Close(); 417 } 418 catch (Exception ex) 419 { 420 Insert_Standard_ErrorLog.Insert("FtpWeb", "ReName Error --> " + ex.Message); 421 } 422 } 423 424 /// <summary> 425 /// 移动文件 426 /// </summary> 427 /// <param name="currentFilename"></param> 428 /// <param name="newFilename"></param> 429 public void MovieFile(string currentFilename, string newDirectory) 430 { 431 ReName(currentFilename, newDirectory); 432 } 433 434 /// <summary> 435 /// 切换当前目录 436 /// </summary> 437 /// <param name="DirectoryName"></param> 438 /// <param name="IsRoot">true 绝对路径 false 相对路径</param> 439 public void GotoDirectory(string DirectoryName, bool IsRoot) 440 { 441 if (IsRoot) 442 { 443 ftpRemotePath = DirectoryName; 444 } 445 else 446 { 447 ftpRemotePath += DirectoryName + "/"; 448 } 449 ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; 450 } 451 452 /// <summary> 453 /// 删除订单目录 454 /// </summary> 455 /// <param name="ftpServerIP">FTP 主机地址</param> 456 /// <param name="folderToDelete">FTP 用户名</param> 457 /// <param name="ftpUserID">FTP 用户名</param> 458 /// <param name="ftpPassword">FTP 密码</param> 459 public static void DeleteOrderDirectory(string ftpServerIP, string folderToDelete, string ftpUserID, string ftpPassword) 460 { 461 try{ 462 if (!string.IsNullOrEmpty(ftpServerIP) && !string.IsNullOrEmpty(folderToDelete) && !string.IsNullOrEmpty(ftpUserID) && !string.IsNullOrEmpty(ftpPassword)) 463 { 464 FtpWeb fw = new FtpWeb(ftpServerIP, folderToDelete, ftpUserID, ftpPassword); 465 //进入订单目录 466 fw.GotoDirectory(folderToDelete, true); 467 //获取规格目录 468 string[] folders = fw.GetDirectoryList(); 469 foreach (string folder in folders) 470 { 471 if (!string.IsNullOrEmpty(folder) || folder != "") 472 { 473 //进入订单目录 474 string subFolder = folderToDelete + "/" + folder; 475 fw.GotoDirectory(subFolder, true); 476 //获取文件列表 477 string[] files = fw.GetFileList("*.*"); 478 if (files != null) 479 { 480 //删除文件 481 foreach (string file in files) 482 { 483 fw.Delete(file); 484 } 485 } 486 //删除冲印规格文件夹 487 fw.GotoDirectory(folderToDelete, true); 488 fw.RemoveDirectory(folder); 489 } 490 } 491 492 //删除订单文件夹 493 string parentFolder = folderToDelete.Remove(folderToDelete.LastIndexOf('/')); 494 string orderFolder = folderToDelete.Substring(folderToDelete.LastIndexOf('/') + 1); 495 fw.GotoDirectory(parentFolder, true); 496 fw.RemoveDirectory(orderFolder); 497 } 498 else 499 { 500 throw new Exception("FTP 及路径不能为空!"); 501 } 502 } 503 catch(Exception ex) 504 { 505 throw new Exception("删除订单时发生错误,错误信息为:" + ex.Message); 506 } 507 } 508 } 509 510 511 public class Insert_Standard_ErrorLog 512 { 513 public static void Insert(string x, string y) 514 { 515 516 } 517 } 518 519 520 }
本文转载自http://www.cnblogs.com/swtseaman/archive/2011/03/29/1998611.html