ftp文件操作类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Net; 6 using System.IO; 7 using System.Data; 8 using System.ComponentModel; 9 using System.Windows.Forms; 10 using System.Text.RegularExpressions; 11 using System.Globalization; 12 using System.Collections; 13 14 namespace ESIMRobot 15 { 16 #region 文件信息结构 17 public struct FileStruct 18 { 19 public string Flags; 20 public string Owner; 21 public string Group; 22 public bool IsDirectory; 23 public DateTime CreateTime; 24 public string Name; 25 } 26 public enum FileListStyle 27 { 28 UnixStyle, 29 WindowsStyle, 30 Unknown 31 } 32 #endregion 33 34 /// <summary> 35 /// ftp文件上传、下载操作类 36 /// </summary> 37 public class FTPHelper 38 { 39 private string ftpServerURL; 40 private string ftpUser; 41 private string ftpPassWord; 42 43 /// <summary> 44 /// 45 /// </summary> 46 /// <param name="ftpServerURL">ftp服务器路径</param> 47 /// <param name="ftpUser">ftp用户名</param> 48 /// <param name="ftpPassWord">ftp用户名</param> 49 public FTPHelper(string ftpServerURL, string ftpUser, string ftpPassWord) 50 { 51 this.ftpServerURL = ftpServerURL; 52 this.ftpUser = ftpUser; 53 this.ftpPassWord = ftpPassWord; 54 } 55 /// <summary> 56 ///通过用户名,密码连接到FTP服务器 57 /// </summary> 58 /// <param name="ftpUser">ftp用户名,匿名为“”</param> 59 /// <param name="ftpPassWord">ftp登陆密码,匿名为“”</param> 60 public FTPHelper(string ftpUser, string ftpPassWord) 61 { 62 this.ftpUser = ftpUser; 63 this.ftpPassWord = ftpPassWord; 64 } 65 66 /// <summary> 67 /// 匿名访问 68 /// </summary> 69 public FTPHelper(string ftpURL) 70 { 71 this.ftpUser = ""; 72 this.ftpPassWord = ""; 73 } 74 75 76 //**************************************************** Start_1 *********************************************************// 77 /// <summary> 78 /// 从FTP下载文件到本地服务器,支持断点下载 79 /// </summary> 80 /// <param name="ftpFilePath">ftp文件路径,如"ftp://localhost/test.txt"</param> 81 /// <param name="saveFilePath">保存文件的路径,如C:\\test.txt</param> 82 public void BreakPointDownLoadFile(string ftpFilePath, string saveFilePath) 83 { 84 System.IO.FileStream fs = null; 85 System.Net.FtpWebResponse ftpRes = null; 86 System.IO.Stream resStrm = null; 87 try 88 { 89 //下载文件的URI 90 Uri uri = new Uri(ftpFilePath); 91 //设定下载文件的保存路径 92 string downFile = saveFilePath; 93 94 //FtpWebRequest的作成 95 System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest) 96 System.Net.WebRequest.Create(uri); 97 //设定用户名和密码 98 ftpReq.Credentials = new System.Net.NetworkCredential(ftpUser, ftpPassWord); 99 //MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定 100 ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; 101 //要求终了后关闭连接 102 ftpReq.KeepAlive = false; 103 //使用ASCII方式传送 104 ftpReq.UseBinary = false; 105 //设定PASSIVE方式无效 106 ftpReq.UsePassive = false; 107 108 //判断是否继续下载 109 //继续写入下载文件的FileStream 110 if (System.IO.File.Exists(downFile)) 111 { 112 //继续下载 113 ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length; 114 fs = new System.IO.FileStream( 115 downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write); 116 } 117 else 118 { 119 //一般下载 120 fs = new System.IO.FileStream( 121 downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write); 122 } 123 124 //取得FtpWebResponse 125 ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse(); 126 //为了下载文件取得Stream 127 resStrm = ftpRes.GetResponseStream(); 128 //写入下载的数据 129 byte[] buffer = new byte[1024]; 130 while (true) 131 { 132 int readSize = resStrm.Read(buffer, 0, buffer.Length); 133 if (readSize == 0) 134 break; 135 fs.Write(buffer, 0, readSize); 136 } 137 } 138 catch (Exception ex) 139 { 140 throw new Exception("从ftp服务器下载文件出错,文件名:" + ftpFilePath + "异常信息:" + ex.ToString()); 141 } 142 finally 143 { 144 fs.Close(); 145 resStrm.Close(); 146 ftpRes.Close(); 147 } 148 } 149 150 151 #region 152 //从FTP上下载整个文件夹,包括文件夹下的文件和文件夹函数列表 153 154 /// <summary> 155 /// 从ftp下载文件到本地服务器 156 /// </summary> 157 /// <param name="ftpFilePath">要下载的ftp文件路径,如ftp://192.168.1.104/capture-2.avi</param> 158 /// <param name="saveFilePath">本地保存文件的路径,如(@"d:\capture-22.avi"</param> 159 public void DownLoadFile(string ftpFilePath, string saveFilePath) 160 { 161 Stream responseStream = null; 162 FileStream fileStream = null; 163 StreamReader reader = null; 164 try 165 { 166 // string downloadUrl = "ftp://192.168.1.104/capture-2.avi"; 167 FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(ftpFilePath); 168 downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile; 169 downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 170 FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse(); 171 responseStream = downloadResponse.GetResponseStream(); 172 173 fileStream = File.Create(saveFilePath); 174 byte[] buffer = new byte[1024]; 175 int bytesRead; 176 while (true) 177 { 178 bytesRead = responseStream.Read(buffer, 0, buffer.Length); 179 if (bytesRead == 0) 180 break; 181 fileStream.Write(buffer, 0, bytesRead); 182 } 183 } 184 catch (Exception ex) 185 { 186 throw new Exception("从ftp服务器下载文件出错,文件名:" + ftpFilePath + "异常信息:" + ex.ToString()); 187 } 188 finally 189 { 190 if (reader != null) 191 { 192 reader.Close(); 193 } 194 if (responseStream != null) 195 { 196 responseStream.Close(); 197 } 198 if (fileStream != null) 199 { 200 fileStream.Close(); 201 } 202 } 203 } 204 205 206 /// <summary> 207 /// 列出当前目录下的所有文件和目录 208 /// </summary> 209 /// <param name="ftpDirPath">FTP目录</param> 210 /// <returns></returns> 211 public List<FileStruct> ListCurrentDirFilesAndChildDirs(string ftpDirPath) 212 { 213 WebResponse webresp = null; 214 StreamReader ftpFileListReader = null; 215 FtpWebRequest ftpRequest = null; 216 try 217 { 218 ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirPath)); 219 ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 220 ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 221 webresp = ftpRequest.GetResponse(); 222 ftpFileListReader = new StreamReader(webresp.GetResponseStream(),Encoding.GetEncoding("UTF-8")); 223 } 224 catch (Exception ex) 225 { 226 throw new Exception("获取文件列表出错,错误信息如下:" + ex.ToString()); 227 } 228 string Datastring = ftpFileListReader.ReadToEnd(); 229 return GetListX(Datastring); 230 231 } 232 233 /// <summary> 234 /// 列出当前目录下的所有文件 235 /// </summary> 236 /// <param name="ftpDirPath">FTP目录</param> 237 /// <returns></returns> 238 public List<FileStruct> ListCurrentDirFiles(string ftpDirPath) 239 { 240 List<FileStruct> listAll = ListCurrentDirFilesAndChildDirs(ftpDirPath); 241 List<FileStruct> listFile = new List<FileStruct>(); 242 foreach (FileStruct file in listAll) 243 { 244 if (!file.IsDirectory) 245 { 246 listFile.Add(file); 247 } 248 } 249 return listFile; 250 } 251 252 253 /// <summary> 254 /// 列出当前目录下的所有子目录 255 /// </summary> 256 /// <param name="ftpDirath">FRTP目录</param> 257 /// <returns>目录列表</returns> 258 public List<FileStruct> ListCurrentDirChildDirs(string ftpDirath) 259 { 260 List<FileStruct> listAll = ListCurrentDirFilesAndChildDirs(ftpDirath); 261 List<FileStruct> listDirectory = new List<FileStruct>(); 262 foreach (FileStruct file in listAll) 263 { 264 if (file.IsDirectory) 265 { 266 listDirectory.Add(file); 267 } 268 } 269 return listDirectory; 270 } 271 272 273 /// <summary> 274 /// 获得文件和目录列表(返回类型为: List<FileStruct> ) 275 /// </summary> 276 /// <param name="datastring">FTP返回的列表字符信息</param> 277 private List<FileStruct> GetListX(string datastring) 278 { 279 List<FileStruct> myListArray = new List<FileStruct>(); 280 string[] dataRecords = datastring.Split('\n'); 281 FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords); 282 foreach (string s in dataRecords) 283 { 284 if (_directoryListStyle != FileListStyle.Unknown && s != "") 285 { 286 FileStruct f = new FileStruct(); 287 f.Name = ".."; 288 switch (_directoryListStyle) 289 { 290 case FileListStyle.UnixStyle: 291 f = ParseFileStructFromUnixStyleRecord(s); 292 break; 293 case FileListStyle.WindowsStyle: 294 f = ParseFileStructFromWindowsStyleRecord(s); 295 break; 296 } 297 if (!(f.Name == "." || f.Name == "..")) 298 { 299 myListArray.Add(f); 300 } 301 } 302 } 303 return myListArray; 304 } 305 /// <summary> 306 /// 从Unix格式中返回文件信息 307 /// </summary> 308 /// <param name="Record">文件信息</param> 309 private FileStruct ParseFileStructFromUnixStyleRecord(string Record) 310 { 311 FileStruct f = new FileStruct(); 312 string processstr = Record.Trim(); 313 f.Flags = processstr.Substring(0, 10); 314 f.IsDirectory = (f.Flags[0] == 'd'); 315 processstr = (processstr.Substring(11)).Trim(); 316 cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分 317 f.Owner = cutSubstringFromStringWithTrim(ref processstr, ' ', 0); 318 f.Group = cutSubstringFromStringWithTrim(ref processstr, ' ', 0); 319 cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分 320 string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2]; 321 if (yearOrTime.IndexOf(":") >= 0) //time 322 { 323 processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString()); 324 } 325 f.CreateTime = DateTime.Parse(cutSubstringFromStringWithTrim(ref processstr, ' ', 8)); 326 f.Name = processstr; //最后就是名称 327 return f; 328 } 329 330 /// <summary> 331 /// 从Windows格式中返回文件信息 332 /// </summary> 333 /// <param name="Record">文件信息</param> 334 private FileStruct ParseFileStructFromWindowsStyleRecord(string Record) 335 { 336 FileStruct f = new FileStruct(); 337 string processstr = Record.Trim(); 338 string dateStr = processstr.Substring(0, 8); 339 processstr = (processstr.Substring(8, processstr.Length - 8)).Trim(); 340 string timeStr = processstr.Substring(0, 7); 341 processstr = (processstr.Substring(7, processstr.Length - 7)).Trim(); 342 DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat; 343 myDTFI.ShortTimePattern = "t"; 344 f.CreateTime = DateTime.Parse(dateStr + " " + timeStr, myDTFI); 345 if (processstr.Substring(0, 5) == "<DIR>") 346 { 347 f.IsDirectory = true; 348 processstr = (processstr.Substring(5, processstr.Length - 5)).Trim(); 349 } 350 else 351 { 352 string[] strs = processstr.Split(new char[] { ' ' }, 2);// StringSplitOptions.RemoveEmptyEntries); // true); 353 processstr = strs[1]; 354 f.IsDirectory = false; 355 } 356 f.Name = processstr; 357 return f; 358 } 359 360 361 /// <summary> 362 /// 按照一定的规则进行字符串截取 363 /// </summary> 364 /// <param name="s">截取的字符串</param> 365 /// <param name="c">查找的字符</param> 366 /// <param name="startIndex">查找的位置</param> 367 private string cutSubstringFromStringWithTrim(ref string s, char c, int startIndex) 368 { 369 int pos1 = s.IndexOf(c, startIndex); 370 string retString = s.Substring(0, pos1); 371 s = (s.Substring(pos1)).Trim(); 372 return retString; 373 } 374 375 376 /// <summary> 377 /// 判断文件列表的方式Window方式还是Unix方式 378 /// </summary> 379 /// <param name="recordList">文件信息列表</param> 380 private FileListStyle GuessFileListStyle(string[] recordList) 381 { 382 foreach (string s in recordList) 383 { 384 if (s.Length > 10 385 && Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)")) 386 { 387 return FileListStyle.UnixStyle; 388 } 389 else if (s.Length > 8 390 && Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]")) 391 { 392 return FileListStyle.WindowsStyle; 393 } 394 } 395 return FileListStyle.Unknown; 396 } 397 398 399 /// <summary> 400 /// 从FTP下载整个文件夹 401 /// </summary> 402 /// <param name="ftpDirPath">FTP文件夹路径</param> 403 /// <param name="saveDirPath">保存的本地文件夹路径</param> 404 /// 调用实例: DownFtpDir("FTP://192.168.1.113/WangJin", @"C:\QMDownload\SoftMgr"); 405 /// 当调用的时候先判断saveDirPath的子目录中是否有WangJin目录,有则执行,没有创建后执行 406 /// 最终文件保存在@"C:\QMDownload\SoftMgr\WangJin"下 407 public bool DownFtpDir(string ftpDirPath, string saveDirPath) 408 { 409 bool success = true; 410 try 411 { 412 List<FileStruct> files = ListCurrentDirFilesAndChildDirs(ftpDirPath); 413 if (!Directory.Exists(saveDirPath)) 414 { 415 Directory.CreateDirectory(saveDirPath); 416 } 417 foreach (FileStruct f in files) 418 { 419 if (f.IsDirectory) //文件夹,递归查询 420 { 421 DownFtpDir(ftpDirPath + "/" + f.Name, saveDirPath + "\\" + f.Name); 422 } 423 else //文件,直接下载 424 { 425 DownLoadFile(ftpDirPath + "/" + f.Name, saveDirPath + "\\" + f.Name); 426 } 427 } 428 } 429 catch (Exception e) 430 { 431 MessageBox.Show(e.Message); 432 success = false; 433 } 434 return success; 435 } 436 #endregion 437 438 439 440 /// <summary> 441 /// 列出当前目录下的所有子目录和文件到TreeView控件中 442 /// </summary> 443 /// <param name="ftpDirPath"> FTP服务器目录 </param> 444 /// <param name="treeview">显示到TreeView控件中</param> 445 /// <param name="treenode">TreeView控件的子节点</param> 446 public void ListCurrentDirFilesAndDirToTreeView(string ftpDirPath, TreeView treeview, TreeNode treenode) 447 { 448 if (ftpDirPath == "") 449 { 450 ftpDirPath = ftpServerURL; 451 } 452 if (treeview != null) 453 { 454 treeview.Nodes.Clear(); 455 treenode = treeview.Nodes.Add(ftpDirPath); 456 } 457 List<FileStruct> files = ListCurrentDirFilesAndChildDirs(ftpDirPath); 458 foreach (FileStruct f in files) 459 { 460 if (f.IsDirectory) //如果为目录(文件夹),递归调用 461 { 462 TreeNode td = treenode.Nodes.Add(f.Name); 463 ListCurrentDirFilesAndDirToTreeView(ftpDirPath + "/" + f.Name, null, td); 464 } 465 else //如果为文件,直接加入到节点中 466 { 467 treenode.Nodes.Add(f.Name); 468 } 469 } 470 } 471 //************************************* End_1 ****************************// 472 473 474 475 476 //************************************ Start_2 ***************************// 477 /// <summary> 478 /// 检测文件或文件目录是否存在 479 /// </summary> 480 /// <param name="ftpDirPath">ftp服务器中的目录路径</param> 481 /// <param name="ftpDirORFileName">待检测的文件或文件名</param> 482 /// <returns></returns> 483 /// 操作实例: ftpclient.fileOrDirCheckExist("FTP://192.168.1.113/Record/", "") 484 /// ftpclient.fileOrDirCheckExist("FTP://192.168.1.113/RecordFile/", "333.txt") 485 public bool fileOrDirCheckExist(string ftpDirPath, string ftpDirORFileName) 486 { 487 bool success = true; 488 FtpWebRequest ftpWebRequest = null; 489 WebResponse webResponse = null; 490 StreamReader reader = null; 491 try 492 { 493 string url = ftpDirPath + ftpDirORFileName; 494 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); 495 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 496 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory; 497 ftpWebRequest.KeepAlive = false; 498 webResponse = ftpWebRequest.GetResponse(); 499 reader = new StreamReader(webResponse.GetResponseStream()); 500 string line = reader.ReadLine(); 501 while (line != null) 502 { 503 if (line == ftpDirORFileName) 504 { 505 break; 506 } 507 line = reader.ReadLine(); 508 } 509 } 510 catch (Exception) 511 { 512 success = false; 513 } 514 finally 515 { 516 if (reader != null) 517 { 518 reader.Close(); 519 } 520 if (webResponse != null) 521 { 522 webResponse.Close(); 523 } 524 } 525 return success; 526 } 527 528 529 /// <summary> 530 /// 获得文件和目录列表(返回类型为:FileStruct) 531 /// </summary> 532 /// <param name="datastring">FTP返回的列表字符信息</param> 533 public FileStruct GetList(string datastring) 534 { 535 FileStruct f = new FileStruct(); 536 string[] dataRecords = datastring.Split('\n'); 537 FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords); 538 if (_directoryListStyle != FileListStyle.Unknown && datastring != "") 539 { 540 541 switch (_directoryListStyle) 542 { 543 case FileListStyle.UnixStyle: 544 f = ParseFileStructFromUnixStyleRecord(datastring); 545 break; 546 case FileListStyle.WindowsStyle: 547 f = ParseFileStructFromWindowsStyleRecord(datastring); 548 break; 549 } 550 } 551 return f; 552 } 553 554 555 /// <summary> 556 /// 上传 557 /// </summary> 558 /// <param name="localFilePath">本地文件名路径</param> 559 /// <param name="ftpDirPath">上传到ftp中目录的路径</param> 560 /// <param name="ftpFileName">上传到ftp中目录的文件名</param> 561 /// <param name="fileLength">限制上传文件的大小(Bytes为单位)</param> 562 /// 操作实例: ftpclient.fileUpload(@"E:\bin\Debug\Web\RecordFile\wangjin\wangjin.txt", "FTP://192.168.1.113/Record/","123.txt",0 ); 563 public bool UploadFile(FileInfo localFilePath, string ftpDirPath, string ftpFileName, long fileLength) 564 { 565 bool success = true; 566 long filesize = 0; 567 FtpWebRequest ftpWebRequest = null; 568 FileStream localFileStream = null; 569 Stream requestStream = null; 570 if (fileLength > 0) 571 { 572 filesize = fileLength * 1024 * 1024; 573 } 574 if (localFilePath.Length <= filesize || filesize == 0) 575 { 576 if (fileOrDirCheckExist(ftpDirPath.Substring(0, ftpDirPath.LastIndexOf(@"/") + 1), ftpDirPath.Substring(ftpDirPath.LastIndexOf(@"/") + 1))) 577 { 578 try 579 { 580 string uri = ftpDirPath + ftpFileName; 581 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 582 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 583 ftpWebRequest.UseBinary = true; 584 ftpWebRequest.KeepAlive = false; 585 ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile; 586 ftpWebRequest.ContentLength = localFilePath.Length; 587 int buffLength = 2048; //定义缓存大小2KB 588 byte[] buff = new byte[buffLength]; 589 int contentLen; 590 localFileStream = localFilePath.OpenRead(); 591 requestStream = ftpWebRequest.GetRequestStream(); 592 contentLen = localFileStream.Read(buff, 0, buffLength); 593 while (contentLen != 0) 594 { 595 requestStream.Write(buff, 0, contentLen); 596 contentLen = localFileStream.Read(buff, 0, buffLength); 597 } 598 } 599 catch (Exception) 600 { 601 success = false; 602 } 603 finally 604 { 605 if (requestStream != null) 606 { 607 requestStream.Close(); 608 } 609 if (localFileStream != null) 610 { 611 localFileStream.Close(); 612 } 613 } 614 } 615 else 616 { 617 success = false; 618 MessageBox.Show("FTP文件路径不存在!"); 619 } 620 } 621 else 622 { 623 success = false; 624 MessageBox.Show("文件大小超过设置范围!" + "\n" + "文件实际大小为:" + localFilePath.Length + "\n" + "允许上传阈值为:" + (5 * 1024 * 1024).ToString()); 625 } 626 return success; 627 } 628 629 /// <summary> 630 /// 下载文件 631 /// </summary> 632 /// <param name="ftpFilePath">需要下载的文件名路径</param> 633 /// <param name="localFilePath">本地保存的文件名路径)</param> 634 /// 操作实例: ftpclient.fileDownload(@"E:\bin\Debug\Web\RecordFile\wangjin\459.txt", "FTP://192.168.1.113/Record/123.txt"); 635 public bool DownloadFile( string localFilePath, string ftpFilePath) 636 { 637 bool success = true; 638 FtpWebRequest ftpWebRequest = null; 639 FtpWebResponse ftpWebResponse = null; 640 Stream ftpResponseStream = null; 641 FileStream outputStream = null; 642 try 643 { 644 outputStream = new FileStream(localFilePath, FileMode.Create); 645 string uri = ftpFilePath; 646 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 647 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 648 ftpWebRequest.UseBinary = true; 649 ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile; 650 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); 651 ftpResponseStream = ftpWebResponse.GetResponseStream(); 652 long contentLength = ftpWebResponse.ContentLength; 653 int bufferSize = 2048; 654 byte[] buffer = new byte[bufferSize]; 655 int readCount; 656 readCount = ftpResponseStream.Read(buffer, 0, bufferSize); 657 while (readCount > 0) 658 { 659 outputStream.Write(buffer, 0, readCount); 660 readCount = ftpResponseStream.Read(buffer, 0, bufferSize); 661 } 662 } 663 catch (Exception) 664 { 665 success = false; 666 } 667 finally 668 { 669 if (outputStream != null) 670 { 671 outputStream.Close(); 672 } 673 if (ftpResponseStream != null) 674 { 675 ftpResponseStream.Close(); 676 } 677 if (ftpWebResponse != null) 678 { 679 ftpWebResponse.Close(); 680 } 681 } 682 return success; 683 } 684 685 686 /// <summary> 687 /// 重命名 688 /// </summary> 689 /// <param name="ftpDirPath">ftp服务器中的目录</param> 690 /// <param name="currentFilename">当前要修改的文件名</param> 691 /// <param name="newFilename">修改后的新文件名</param> 692 /// 操作实例: ftpclientxy.fileRename("FTP://192.168.1.113/RecordFile/", "123.txt", "333.txt"); 693 public bool RenameFile(string ftpDirPath, string currentFileName, string newFileName) 694 { 695 bool success = true; 696 FtpWebRequest ftpWebRequest = null; 697 FtpWebResponse ftpWebResponse = null; 698 Stream ftpResponseStream = null; 699 if (fileOrDirCheckExist(ftpDirPath.Substring(0, ftpDirPath.LastIndexOf(@"/") + 1), ftpDirPath.Substring(ftpDirPath.LastIndexOf(@"/") + 1))) 700 { 701 try 702 { 703 string uri = ftpDirPath + currentFileName; 704 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 705 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 706 ftpWebRequest.UseBinary = true; 707 ftpWebRequest.Method = WebRequestMethods.Ftp.Rename; 708 ftpWebRequest.RenameTo = newFileName; 709 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); 710 ftpResponseStream = ftpWebResponse.GetResponseStream(); 711 } 712 catch (Exception) 713 { 714 success = false; 715 } 716 finally 717 { 718 if (ftpResponseStream != null) 719 { 720 ftpResponseStream.Close(); 721 } 722 if (ftpWebResponse != null) 723 { 724 ftpWebResponse.Close(); 725 } 726 } 727 } 728 else 729 { 730 success = false; 731 MessageBox.Show("FTP文件路径不存在!"); 732 } 733 return success; 734 } 735 736 /// <summary> 737 /// 在目录下创建子目录 738 /// </summary> 739 /// <param name="ftpDirPath">ftp服务器中的目录</param> 740 /// <param name="ftpFileDir">待创建的子目录</param> 741 /// <returns></returns> 742 /// 操作实例: ftpclient.fileDirMake("FTP://192.168.1.113/RecordFile/", "WangJinFile") 743 public bool MakeDir(string ftpDirPath, string ftpFileDir) 744 { 745 bool success = true; 746 FtpWebRequest ftpWebRequest = null; 747 WebResponse webResponse = null; 748 StreamReader reader = null; 749 try 750 { 751 string url = ftpDirPath + ftpFileDir; 752 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); 753 // 指定数据传输类型 754 ftpWebRequest.UseBinary = true; 755 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 756 ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory; 757 webResponse = ftpWebRequest.GetResponse(); 758 } 759 catch (Exception) 760 { 761 success = false; 762 } 763 finally 764 { 765 if (reader != null) 766 { 767 reader.Close(); 768 } 769 if (webResponse != null) 770 { 771 webResponse.Close(); 772 } 773 } 774 return success; 775 } 776 777 778 /// <summary> 779 /// 删除目录中的文件 780 /// </summary> 781 /// <param name="ftpDirPath"></param> 782 /// <param name="ftpFileName"></param> 783 /// <returns></returns> 784 /// 操作实例: ftpclient.fileDelete("FTP://192.168.1.113/RecordFile/WangJinFile/", "333.txt") 785 public bool DeleteFile(string ftpDirPath, string ftpFileName) 786 { 787 bool success = true; 788 FtpWebRequest ftpWebRequest = null; 789 FtpWebResponse ftpWebResponse = null; 790 Stream ftpResponseStream = null; 791 StreamReader streamReader = null; 792 try 793 { 794 string uri = ftpDirPath + ftpFileName; 795 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 796 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 797 ftpWebRequest.KeepAlive = false; 798 ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile; 799 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); 800 long size = ftpWebResponse.ContentLength; 801 ftpResponseStream = ftpWebResponse.GetResponseStream(); 802 streamReader = new StreamReader(ftpResponseStream); 803 string result = String.Empty; 804 result = streamReader.ReadToEnd(); 805 } 806 catch (Exception) 807 { 808 success = false; 809 } 810 finally 811 { 812 if (streamReader != null) 813 { 814 streamReader.Close(); 815 } 816 if (ftpResponseStream != null) 817 { 818 ftpResponseStream.Close(); 819 } 820 if (ftpWebResponse != null) 821 { 822 ftpWebResponse.Close(); 823 } 824 } 825 return success; 826 } 827 828 /// <summary> 829 /// 获取目录的子目录数组 830 /// </summary> 831 /// <param name="ftpDirPath"></param> 832 /// <returns></returns> 833 /// 操作实例: string []filedir = ftpclient.GetDeleteFolderArray("FTP://192.168.1.113/WangJinFile/"); 834 public string[] GetDirArray(string ftpDirPath) 835 { 836 string[] deleteFolders; 837 FtpWebRequest ftpWebRequest = null; 838 FtpWebResponse ftpWebResponse = null; 839 Stream ftpResponseStream = null; 840 StreamReader streamReader = null; 841 StringBuilder result = new StringBuilder(); 842 try 843 { 844 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirPath)); 845 ftpWebRequest.UseBinary = true; 846 ftpWebRequest.UsePassive = false; 847 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 848 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 849 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); 850 Encoding encoding = Encoding.GetEncoding("UTF-8"); 851 ftpResponseStream = ftpWebResponse.GetResponseStream(); 852 streamReader = new StreamReader(ftpResponseStream, encoding); 853 streamReader = new StreamReader(ftpResponseStream); 854 String line = streamReader.ReadLine(); 855 bool flag = false; 856 while (line != null) 857 { 858 FileStruct f = new FileStruct(); 859 f = GetList(line); 860 String fileName = f.Name; 861 if (f.IsDirectory) 862 { 863 result.Append(fileName); 864 result.Append("\n"); 865 flag = true; 866 line = streamReader.ReadLine(); 867 continue; 868 } 869 line = streamReader.ReadLine(); 870 } 871 streamReader.Close(); 872 ftpWebResponse.Close(); 873 if (flag) 874 { 875 result.Remove(result.ToString().LastIndexOf("\n"), 1); 876 return result.ToString().Split('\n'); 877 } 878 else 879 { 880 deleteFolders = null; 881 return deleteFolders; 882 } 883 } 884 catch (Exception ex) 885 { 886 MessageBox.Show(ex.ToString(), "获取文件夹数组过程中出现异常"); 887 deleteFolders = null; 888 return deleteFolders; 889 } 890 } 891 892 /// <summary> 893 /// 获取目录中文件数组 894 /// </summary> 895 /// <param name="ftpDirPath"></param> 896 /// <returns></returns> 897 /// 操作实例: string []filedir_Childrenfiles = ftpclient.GetDeleteFolderArray("FTP://192.168.1.113/WangJinFile/"); 898 public string[] GetFileArray(string ftpDirPath) 899 { 900 string[] DeleteFiles; 901 FtpWebRequest ftpWebRequest = null; 902 FtpWebResponse ftpWebResponse = null; 903 Stream ftpResponseStream = null; 904 StreamReader streamReader = null; 905 StringBuilder result = new StringBuilder(); 906 try 907 { 908 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirPath)); 909 ftpWebRequest.UseBinary = true; 910 ftpWebRequest.UsePassive = false; 911 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 912 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 913 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); 914 Encoding encoding = Encoding.GetEncoding("UTF-8"); 915 ftpResponseStream = ftpWebResponse.GetResponseStream(); 916 streamReader = new StreamReader(ftpResponseStream, encoding); 917 streamReader = new StreamReader(ftpResponseStream); 918 String line = streamReader.ReadLine(); 919 bool flag = false; 920 while (line != null) 921 { 922 FileStruct f = new FileStruct(); 923 f = GetList(line); 924 String fileName = f.Name; 925 //排除非文件夹 926 if (!f.IsDirectory) 927 { 928 result.Append(fileName); 929 result.Append("\n"); 930 flag = true; 931 line = streamReader.ReadLine(); 932 continue; 933 } 934 line = streamReader.ReadLine(); 935 } 936 streamReader.Close(); 937 ftpWebResponse.Close(); 938 if (flag) 939 { 940 result.Remove(result.ToString().LastIndexOf("\n"), 1); 941 return result.ToString().Split('\n'); 942 } 943 else 944 { 945 DeleteFiles = null; 946 return DeleteFiles; 947 } 948 } 949 catch (Exception ex) 950 { 951 MessageBox.Show(ex.ToString(), "获取文件数组过程中出现异常"); 952 DeleteFiles = null; 953 return DeleteFiles; 954 } 955 } 956 957 /// <summary> 958 /// 删除目录中的文件 959 /// </summary> 960 /// <param name="ftpFilePath"> 待删除的目录中的文件路径</param> 961 /// <returns></returns> 962 /// ftpclient.DeleteChilderFile("FTP://192.168.1.113/WangJinFile/bin/From1.cs") 963 private bool DeleteFile(string ftpFilePath) 964 { 965 bool success = true; 966 FtpWebRequest ftpWebRequest = null; 967 FtpWebResponse ftpWebResponse = null; 968 try 969 { 970 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpFilePath)); 971 ftpWebRequest.UseBinary = true; 972 ftpWebRequest.UsePassive = false; 973 ftpWebRequest.KeepAlive = false; 974 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 975 ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile; 976 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); 977 ftpWebResponse.Close(); 978 } 979 catch (Exception ex) 980 { 981 success = false; 982 MessageBox.Show(ex.ToString(), "删除文件过程中出现错误"); 983 } 984 return success; 985 } 986 987 /// <summary> 988 /// 删除目录(条件为:该目录无文件) 989 /// </summary> 990 /// <param name="ftpDirPath">为所要删除的文件的全路径</param> 991 /// 操作实例: ftpclient.DeleteFileDir("FTP://192.168.1.113/WangJinFile/bin/") 992 public bool DeleteNullFileDir(string ftpDirPath) 993 { 994 bool success = true; 995 FtpWebRequest ftpWebRequest = null; 996 FtpWebResponse ftpWebResponse = null; 997 try 998 { 999 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirPath)); 1000 ftpWebRequest.UseBinary = true; 1001 ftpWebRequest.UsePassive = false; 1002 ftpWebRequest.KeepAlive = false; 1003 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); 1004 ftpWebRequest.Method = WebRequestMethods.Ftp.RemoveDirectory; 1005 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); 1006 ftpWebResponse.Close(); 1007 } 1008 catch (Exception ex) 1009 { 1010 success = false; 1011 MessageBox.Show(ex.ToString(), "删除文件夹过程中出现错误"); 1012 } 1013 return success; 1014 } 1015 1016 1017 1018 /// <summary> 1019 /// 删除目录和文件 1020 /// </summary> 1021 /// <param name="ftpDirPath">待删除的目录(包含子目录和文件)</param> 1022 /// 调用实例: ftpclient.DeleteFileDirAndChilderFiles("FTP://192.168.1.113/RecordFile/WangJinFile") 1023 public bool DeleteDirAndFiles(string ftpDirPath) 1024 { 1025 bool success = true; 1026 try 1027 { 1028 string[] folderArray = GetDirArray(ftpDirPath + @"/"); 1029 string[] fileArray = GetFileArray(ftpDirPath + @"/"); 1030 ArrayList folderArrayList = new ArrayList(); 1031 ArrayList fileArrayList = new ArrayList(); 1032 //重新构造存放文件夹的数组(用动态数组实现) 1033 if (folderArray != null) 1034 { 1035 for (int i = 0; i < folderArray.Length; i++) 1036 { 1037 if (folderArray[i] == "." || folderArray[i] == ".." || folderArray[i] == "") 1038 { 1039 } 1040 else 1041 { 1042 folderArrayList.Add(folderArray[i]); 1043 } 1044 } 1045 } 1046 if (fileArray != null) 1047 { 1048 //重新构造存放文件的数组(用动态数组实现) 1049 for (int i = 0; i < fileArray.Length; i++) 1050 { 1051 if (fileArray[i] == "") 1052 { 1053 } 1054 else 1055 { 1056 fileArrayList.Add(fileArray[i]); 1057 } 1058 } 1059 } 1060 if (folderArrayList.Count == 0 && fileArrayList.Count == 0) //选定目录中: 子目录 = 0, 子文件 = 0 1061 { 1062 DeleteNullFileDir(ftpDirPath); 1063 } 1064 else if (folderArrayList.Count == 0 && fileArrayList.Count != 0) //选定目录中: 子目录 = 0, 子文件 > 0 1065 { 1066 //删除所有子文件 1067 for (int i = 0; i < fileArrayList.Count; i++) 1068 { 1069 string fileUri = ftpDirPath + "/" + fileArrayList[i]; 1070 DeleteFile(fileUri); 1071 } 1072 //删除选定目录 1073 DeleteNullFileDir(ftpDirPath); 1074 } 1075 else if (folderArrayList.Count != 0 && fileArrayList.Count != 0) //选定目录中: 子目录 >0, 子文件 > 0 1076 { 1077 //删除所有子文件 1078 for (int i = 0; i < fileArrayList.Count; i++) 1079 { 1080 string fileUri = ftpDirPath + "/" + fileArrayList[i]; 1081 DeleteFile(fileUri); 1082 } 1083 //删除文件目录 1084 for (int i = 0; i < folderArrayList.Count; i++) 1085 { 1086 string dirUri = ftpDirPath + "/" + folderArrayList[i]; 1087 DeleteDirAndFiles(dirUri); 1088 } 1089 DeleteNullFileDir(ftpDirPath); 1090 } 1091 else if (folderArrayList.Count != 0 && fileArrayList.Count == 0) //选定目录中: 子目录 >0, 子文件 = 0 1092 { 1093 //删除所有子文件 1094 for (int i = 0; i < folderArrayList.Count; i++) 1095 { 1096 string dirUri = ftpDirPath + "/" + folderArrayList[i]; 1097 DeleteDirAndFiles(dirUri); 1098 } 1099 DeleteNullFileDir(ftpDirPath); 1100 } 1101 success = true; 1102 } 1103 catch (Exception ex) 1104 { 1105 success = false; 1106 MessageBox.Show(ex.ToString(), "删除目录过程中出现异常"); 1107 } 1108 return success; 1109 } 1110 1111 //****************************************** End_2 ********************************************// 1112 } 1113 }