C# FTP 實現方式,廢話很少說,直接上代碼服務器
1 public class FtpClient 2 { 3 #region 構造函數 4 /// <summary> 5 /// 建立FTP工具 6 /// <para> 7 /// 默認不使用SSL,使用二進制傳輸方式,使用被動模式 8 /// </para> 9 /// </summary> 10 /// <param name="host">主機名稱</param> 11 /// <param name="userId">用戶名</param> 12 /// <param name="password">密碼</param> 13 public FtpClient(string host, string userId, string password) 14 : this(host, userId, password, 21, null, false, true, true) 15 { 16 } 17 /// <summary> 18 /// 建立FTP工具 19 /// </summary> 20 /// <param name="host">主機名稱</param> 21 /// <param name="userId">用戶名</param> 22 /// <param name="password">密碼</param> 23 /// <param name="port">端口</param> 24 /// <param name="enableSsl">容許Ssl</param> 25 /// <param name="proxy">代理</param> 26 /// <param name="useBinary">容許二進制</param> 27 /// <param name="usePassive">容許被動模式</param> 28 public FtpClient(string host, string userId, string password, int port, IWebProxy proxy, bool enableSsl, bool useBinary, bool usePassive) 29 { 30 this.userId = userId; 31 this.password = password; 32 if (host.ToLower().StartsWith("ftp://")) 33 { 34 this.host = host; 35 } 36 else 37 { 38 this.host = "ftp://" + host; 39 } 40 this.port = port; 41 this.proxy = proxy; 42 this.enableSsl = enableSsl; 43 this.useBinary = useBinary; 44 this.usePassive = usePassive; 45 } 46 #endregion 47 #region 主機 48 private string host = string.Empty; 49 /// <summary> 50 /// 主機 51 /// </summary> 52 public string Host 53 { 54 get 55 { 56 return this.host ?? string.Empty; 57 } 58 } 59 #endregion 60 #region 登陸用戶名 61 private string userId = string.Empty; 62 /// <summary> 63 /// 登陸用戶名 64 /// </summary> 65 public string UserId 66 { 67 get 68 { 69 return this.userId; 70 } 71 } 72 #endregion 73 #region 密碼 74 private string password = string.Empty; 75 /// <summary> 76 /// 密碼 77 /// </summary> 78 public string Password 79 { 80 get 81 { 82 return this.password; 83 } 84 } 85 #endregion 86 #region 代理 87 IWebProxy proxy = null; 88 /// <summary> 89 /// 代理 90 /// </summary> 91 public IWebProxy Proxy 92 { 93 get 94 { 95 return this.proxy; 96 } 97 set 98 { 99 this.proxy = value; 100 } 101 } 102 #endregion 103 #region 端口 104 private int port = 21; 105 /// <summary> 106 /// 端口 107 /// </summary> 108 public int Port 109 { 110 get 111 { 112 return port; 113 } 114 set 115 { 116 this.port = value; 117 } 118 } 119 #endregion 120 #region 設置是否容許Ssl 121 private bool enableSsl = false; 122 /// <summary> 123 /// EnableSsl 124 /// </summary> 125 public bool EnableSsl 126 { 127 get 128 { 129 return enableSsl; 130 } 131 } 132 #endregion 133 #region 使用被動模式 134 private bool usePassive = true; 135 /// <summary> 136 /// 被動模式 137 /// </summary> 138 public bool UsePassive 139 { 140 get 141 { 142 return usePassive; 143 } 144 set 145 { 146 this.usePassive = value; 147 } 148 } 149 #endregion 150 #region 二進制方式 151 private bool useBinary = true; 152 /// <summary> 153 /// 二進制方式 154 /// </summary> 155 public bool UseBinary 156 { 157 get 158 { 159 return useBinary; 160 } 161 set 162 { 163 this.useBinary = value; 164 } 165 } 166 #endregion 167 #region 遠端路徑 168 private string remotePath = "/"; 169 /// <summary> 170 /// 遠端路徑 171 /// <para> 172 /// 返回FTP服務器上的當前路徑(能夠是 / 或 /a/../ 的形式) 173 /// </para> 174 /// </summary> 175 public string RemotePath 176 { 177 get 178 { 179 return remotePath; 180 } 181 set 182 { 183 string result = "/"; 184 if (!string.IsNullOrEmpty(value) && value != "/") 185 { 186 result = "/" + value.TrimStart('/').TrimEnd('/') + "/"; 187 } 188 this.remotePath = result; 189 } 190 } 191 #endregion 192 #region 建立一個FTP鏈接 193 /// <summary> 194 /// 建立一個FTP請求 195 /// </summary> 196 /// <param name="url">請求地址</param> 197 /// <param name="method">請求方法</param> 198 /// <returns>FTP請求</returns> 199 private FtpWebRequest CreateRequest(string url, string method) 200 { 201 //創建鏈接 202 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url); 203 request.Credentials = new NetworkCredential(this.userId, this.password); 204 request.Proxy = this.proxy; 205 request.KeepAlive = false;//命令執行完畢以後關閉鏈接 206 request.UseBinary = useBinary; 207 request.UsePassive = usePassive; 208 request.EnableSsl = enableSsl; 209 request.Method = method; 210 return request; 211 } 212 #endregion 213 #region 上傳一個文件到遠端路徑下 214 /// <summary> 215 /// 把文件上傳到FTP服務器的RemotePath下 216 /// </summary> 217 /// <param name="localFile">本地文件信息</param> 218 /// <param name="remoteFileName">要保存到FTP文件服務器上的名稱</param> 219 public bool Upload(FileInfo localFile, string remoteFileName) 220 { 221 bool result = false; 222 if (localFile.Exists) 223 { 224 string url = Host.TrimEnd('/') + RemotePath + remoteFileName; 225 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.UploadFile); 226 //上傳數據 227 using (Stream rs = request.GetRequestStream()) 228 using (FileStream fs = localFile.OpenRead()) 229 { 230 byte[] buffer = new byte[4096];//4K 231 int count = fs.Read(buffer, 0, buffer.Length); 232 while (count > 0) 233 { 234 rs.Write(buffer, 0, count); 235 count = fs.Read(buffer, 0, buffer.Length); 236 } 237 fs.Close(); 238 result = true; 239 } 240 return result; 241 } 242 throw new Exception(string.Format("本地文件不存在,文件路徑:{0}", localFile.FullName)); 243 } 244 #endregion 245 #region 從FTP服務器上下載文件 246 /// <summary> 247 /// 從當前目錄下下載文件 248 /// <para> 249 /// 若是本地文件存在,則從本地文件結束的位置開始下載. 250 /// </para> 251 /// </summary> 252 /// <param name="serverName">服務器上的文件名稱</param> 253 /// <param name="localName">本地文件名稱</param> 254 /// <returns>返回一個值,指示是否下載成功</returns> 255 public bool Download(string serverName, string localName) 256 { 257 bool result = false; 258 using (FileStream fs = new FileStream(localName, FileMode.OpenOrCreate)) //建立或打開本地文件 259 { 260 //創建鏈接 261 string url = Host.TrimEnd('/') + RemotePath + serverName; 262 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DownloadFile); 263 request.ContentOffset = fs.Length; 264 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 265 { 266 fs.Position = fs.Length; 267 byte[] buffer = new byte[4096];//4K 268 int count = response.GetResponseStream().Read(buffer, 0, buffer.Length); 269 while (count > 0) 270 { 271 fs.Write(buffer, 0, count); 272 count = response.GetResponseStream().Read(buffer, 0, buffer.Length); 273 } 274 response.GetResponseStream().Close(); 275 } 276 result = true; 277 } 278 return result; 279 } 280 #endregion 281 #region 重命名FTP服務器上的文件 282 /// <summary> 283 /// 文件改名 284 /// </summary> 285 /// <param name="oldFileName">原文件名</param> 286 /// <param name="newFileName">新文件名</param> 287 /// <returns>返回一個值,指示改名是否成功</returns> 288 public bool Rename(string oldFileName, string newFileName) 289 { 290 bool result = false; 291 //創建鏈接 292 string url = Host.TrimEnd('/') + RemotePath + oldFileName; 293 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.Rename); 294 request.RenameTo = newFileName; 295 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 296 { 297 result = true; 298 } 299 return result; 300 } 301 #endregion 302 #region 從當前目錄下獲取文件列表 303 /// <summary> 304 /// 獲取當前目錄下文件列表 305 /// </summary> 306 /// <returns></returns> 307 public List<string> GetFileList() 308 { 309 List<string> result = new List<string>(); 310 //創建鏈接 311 string url = Host.TrimEnd('/') + RemotePath; 312 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectory); 313 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 314 { 315 StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名 316 string line = reader.ReadLine(); 317 while (line != null) 318 { 319 result.Add(line); 320 line = reader.ReadLine(); 321 } 322 } 323 return result; 324 } 325 #endregion 326 #region 從FTP服務器上獲取文件和文件夾列表 327 /// <summary> 328 /// 獲取詳細列表 從FTP服務器上獲取文件和文件夾列表 329 /// </summary> 330 /// <returns></returns> 331 public List<string> GetFileDetails() 332 { 333 List<string> result = new List<string>(); 334 //創建鏈接 335 string url = Host.TrimEnd('/') + RemotePath; 336 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectoryDetails); 337 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 338 { 339 StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名 340 string line = reader.ReadLine(); 341 while (line != null) 342 { 343 result.Add(line); 344 line = reader.ReadLine(); 345 } 346 } 347 return result; 348 } 349 #endregion 350 #region 從FTP服務器上刪除文件 351 /// <summary> 352 /// 刪除FTP服務器上的文件 353 /// </summary> 354 /// <param name="fileName">文件名稱</param> 355 /// <returns>返回一個值,指示是否刪除成功</returns> 356 public bool DeleteFile(string fileName) 357 { 358 bool result = false; 359 //創建鏈接 360 string url = Host.TrimEnd('/') + RemotePath + fileName; 361 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DeleteFile); 362 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 363 { 364 result = true; 365 } 366 return result; 367 } 368 #endregion 369 #region 在FTP服務器上建立目錄 370 /// <summary> 371 /// 在當前目錄下建立文件夾 372 /// </summary> 373 /// <param name="dirName">文件夾名稱</param> 374 /// <returns>返回一個值,指示是否建立成功</returns> 375 public bool MakeDirectory(string dirName) 376 { 377 bool result = false; 378 //創建鏈接 379 string url = Host.TrimEnd('/') + RemotePath + dirName; 380 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.MakeDirectory); 381 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 382 { 383 result = true; 384 } 385 return result; 386 } 387 #endregion 388 #region 從FTP服務器上刪除目錄 389 /// <summary> 390 /// 刪除文件夾 391 /// </summary> 392 /// <param name="dirName">文件夾名稱</param> 393 /// <returns>返回一個值,指示是否刪除成功</returns> 394 public bool DeleteDirectory(string dirName) 395 { 396 bool result = false; 397 //創建鏈接 398 string url = Host.TrimEnd('/') + RemotePath + dirName; 399 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.RemoveDirectory); 400 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 401 { 402 result = true; 403 } 404 return result; 405 } 406 #endregion 407 #region 從FTP服務器上獲取文件大小 408 /// <summary> 409 /// 獲取文件大小 410 /// </summary> 411 /// <param name="fileName"></param> 412 /// <returns></returns> 413 public long GetFileSize(string fileName) 414 { 415 long result = 0; 416 //創建鏈接 417 string url = Host.TrimEnd('/') + RemotePath + fileName; 418 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.GetFileSize); 419 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 420 { 421 result = response.ContentLength; 422 } 423 return result; 424 } 425 #endregion 426 #region 給FTP服務器上的文件追加內容 427 /// <summary> 428 /// 給FTP服務器上的文件追加內容 429 /// </summary> 430 /// <param name="localFile">本地文件</param> 431 /// <param name="remoteFileName">FTP服務器上的文件</param> 432 /// <returns>返回一個值,指示是否追加成功</returns> 433 public bool Append(FileInfo localFile, string remoteFileName) 434 { 435 if (localFile.Exists) 436 { 437 using (FileStream fs = new FileStream(localFile.FullName, FileMode.Open)) 438 { 439 return Append(fs, remoteFileName); 440 } 441 } 442 throw new Exception(string.Format("本地文件不存在,文件路徑:{0}", localFile.FullName)); 443 } 444 /// <summary> 445 /// 給FTP服務器上的文件追加內容 446 /// </summary> 447 /// <param name="stream">數據流(可經過設置偏移來實現從特定位置開始上傳)</param> 448 /// <param name="remoteFileName">FTP服務器上的文件</param> 449 /// <returns>返回一個值,指示是否追加成功</returns> 450 public bool Append(Stream stream, string remoteFileName) 451 { 452 bool result = false; 453 if (stream != null && stream.CanRead) 454 { 455 //創建鏈接 456 string url = Host.TrimEnd('/') + RemotePath + remoteFileName; 457 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.AppendFile); 458 using (Stream rs = request.GetRequestStream()) 459 { 460 //上傳數據 461 byte[] buffer = new byte[4096];//4K 462 int count = stream.Read(buffer, 0, buffer.Length); 463 while (count > 0) 464 { 465 rs.Write(buffer, 0, count); 466 count = stream.Read(buffer, 0, buffer.Length); 467 } 468 result = true; 469 } 470 } 471 return result; 472 } 473 #endregion 474 #region 獲取FTP服務器上的當前路徑 475 /// <summary> 476 /// 獲取FTP服務器上的當前路徑 477 /// </summary> 478 public string CurrentDirectory 479 { 480 get 481 { 482 string result = string.Empty; 483 string url = Host.TrimEnd('/') + RemotePath; 484 FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.PrintWorkingDirectory); 485 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 486 { 487 string temp = response.StatusDescription; 488 int start = temp.IndexOf('"') + 1; 489 int end = temp.LastIndexOf('"'); 490 if (end >= start) 491 { 492 result = temp.Substring(start, end - start); 493 } 494 } 495 return result; 496 } 497 } 498 #endregion 499 #region 檢查當前路徑上是否存在某個文件 500 /// <summary> 501 /// 檢查文件是否存在 502 /// </summary> 503 /// <param name="fileName">要檢查的文件名</param> 504 /// <returns>返回一個值,指示要檢查的文件是否存在</returns> 505 public bool CheckFileExist(string fileName) 506 { 507 bool result = false; 508 if (fileName != null && fileName.Trim().Length > 0) 509 { 510 fileName = fileName.Trim(); 511 List<string> files = GetFileList(); 512 if (files != null && files.Count > 0) 513 { 514 foreach (string file in files) 515 { 516 if (file.ToLower() == fileName.ToLower()) 517 { 518 result = true; 519 break; 520 } 521 } 522 } 523 } 524 return result; 525 } 526 #endregion 527 }