//FTP開源封裝的類
using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
namespace FTP
{
/// <summary>
/// FTP用戶端操作類
/// </summary>
public class FtpClient
{
#region 構造函數
/// <summary>
/// 建立FTP工具
/// <para>
/// 預設不使用SSL,使用二進制傳輸方式,使用被動模式
/// </para>
/// </summary>
/// <param name="host">主機名稱</param>
/// <param name="userId">使用者名</param>
/// <param name="password">密碼</param>
public FtpClient(string host, string userId, string password)
: this(host, userId, password, 21, null, false, true, true)
{
}
/// <param name="port">端口</param>
/// <param name="enableSsl">允許Ssl</param>
/// <param name="proxy">代理</param>
/// <param name="useBinary">允許二進制</param>
/// <param name="usePassive">允許被動模式</param>
public FtpClient(string host, string userId, string password, int port, IWebProxy proxy, bool enableSsl, bool useBinary, bool usePassive)
this.userId = userId;
this.password = password;
if (host.ToLower().StartsWith("ftp://"))
{
this.host = host;
}
else
this.host = "ftp://" + host;
this.port = port;
this.proxy = proxy;
this.enableSsl = enableSsl;
this.useBinary = useBinary;
this.usePassive = usePassive;
#endregion
#region 主機
private string host = string.Empty;
/// 主機
public string Host
get
return this.host ?? string.Empty;
#region 登入使用者名
private string userId = string.Empty;
/// 登入使用者名
public string UserId
return this.userId;
#region 密碼
private string password = string.Empty;
/// 密碼
public string Password
return this.password;
#region 代理
IWebProxy proxy = null;
/// 代理
public IWebProxy Proxy
return this.proxy;
set
this.proxy = value;
#region 端口
private int port = 21;
/// 端口
public int Port
return port;
this.port = value;
#region 設定是否允許Ssl
private bool enableSsl = false;
/// EnableSsl
public bool EnableSsl
return enableSsl;
#region 使用被動模式
private bool usePassive = true;
/// 被動模式
public bool UsePassive
return usePassive;
this.usePassive = value;
#region 二進制方式
private bool useBinary = true;
/// 二進制方式
public bool UseBinary
return useBinary;
this.useBinary = value;
#region 遠端路徑
private string remotePath = "/";
/// 遠端路徑
/// 傳回FTP伺服器上的目前路徑(可以是 / 或 /a/../ 的形式)
public string RemotePath
return remotePath;
string result = "/";
if (!string.IsNullOrEmpty(value) && value != "/")
{
result = "/" + value.TrimStart('/').TrimEnd('/') + "/";
}
this.remotePath = result;
#region 建立一個FTP連接配接
/// 建立一個FTP請求
/// <param name="url">請求位址</param>
/// <param name="method">請求方法</param>
/// <returns>FTP請求</returns>
private FtpWebRequest CreateRequest(string url, string method)
//建立連接配接
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential(this.userId, this.password);
request.Proxy = this.proxy;
request.KeepAlive = false;//指令執行完畢之後關閉連接配接
request.UseBinary = useBinary;
request.UsePassive = usePassive;
request.EnableSsl = enableSsl;
request.Method = method;
return request;
#region 上傳一個檔案到遠端路徑下
/// 把檔案上傳到FTP伺服器的RemotePath下
/// <param name="localFile">本地檔案資訊</param>
/// <param name="remoteFileName">要儲存到FTP檔案伺服器上的名稱</param>
public bool Upload(FileInfo localFile, string remoteFileName)
bool result = false;
if (localFile.Exists)
string url = Host.TrimEnd('/') + RemotePath + remoteFileName;
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.UploadFile);
//上傳資料
using (Stream rs = request.GetRequestStream())
using (FileStream fs = localFile.OpenRead())
byte[] buffer = new byte[4096];//4K
int count = fs.Read(buffer, 0, buffer.Length);
while (count > 0)
{
rs.Write(buffer, 0, count);
count = fs.Read(buffer, 0, buffer.Length);
}
fs.Close();
result = true;
return result;
throw new Exception(string.Format("本地檔案不存在,檔案路徑:{0}", localFile.FullName));
#region 從FTP伺服器上下載下傳檔案
/// 從目前目錄下下載下傳檔案
/// 如果本地檔案存在,則從本地檔案結束的位置開始下載下傳.
/// <param name="serverName">伺服器上的檔案名稱</param>
/// <param name="localName">本地檔案名稱</param>
/// <returns>傳回一個值,訓示是否下載下傳成功</returns>
public bool Download(string serverName, string localName)
using (FileStream fs = new FileStream(localName, FileMode.OpenOrCreate)) //建立或打開本地檔案
//建立連接配接
string url = Host.TrimEnd('/') + RemotePath + serverName;
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DownloadFile);
request.ContentOffset = fs.Length;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
fs.Position = fs.Length;
int count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, count);
count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
response.GetResponseStream().Close();
result = true;
return result;
#region 重命名FTP伺服器上的檔案
/// 檔案更名
/// <param name="oldFileName">原檔案名</param>
/// <param name="newFileName">新檔案名</param>
/// <returns>傳回一個值,訓示更名是否成功</returns>
public bool Rename(string oldFileName, string newFileName)
string url = Host.TrimEnd('/') + RemotePath + oldFileName;
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.Rename);
request.RenameTo = newFileName;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
#region 從目前目錄下擷取檔案清單
/// 擷取目前目錄下檔案清單
/// <returns></returns>
public List<string> GetFileList()
List<string> result = new List<string>();
string url = Host.TrimEnd('/') + RemotePath;
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectory);
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文檔案名
string line = reader.ReadLine();
while (line != null)
result.Add(line);
line = reader.ReadLine();
#region 從FTP伺服器上擷取檔案和檔案夾清單
/// 擷取詳細清單
public List<string> GetFileDetails()
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectoryDetails);
#region 從FTP伺服器上删除檔案
/// 删除FTP伺服器上的檔案
/// <param name="fileName">檔案名稱</param>
/// <returns>傳回一個值,訓示是否删除成功</returns>
public bool DeleteFile(string fileName)
string url = Host.TrimEnd('/') + RemotePath + fileName;
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DeleteFile);
#region 在FTP伺服器上建立目錄
/// 在目前目錄下建立檔案夾
/// <param name="dirName">檔案夾名稱</param>
/// <returns>傳回一個值,訓示是否建立成功</returns>
public bool MakeDirectory(string dirName)
string url = Host.TrimEnd('/') + RemotePath + dirName;
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.MakeDirectory);
#region 從FTP伺服器上删除目錄
/// 删除檔案夾
public bool DeleteDirectory(string dirName)
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.RemoveDirectory);
#region 從FTP伺服器上擷取檔案大小
/// 擷取檔案大小
/// <param name="fileName"></param>
public long GetFileSize(string fileName)
long result = 0;
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.GetFileSize);
result = response.ContentLength;
#region 給FTP伺服器上的檔案追加内容
/// 給FTP伺服器上的檔案追加内容
/// <param name="localFile">本地檔案</param>
/// <param name="remoteFileName">FTP伺服器上的檔案</param>
/// <returns>傳回一個值,訓示是否追加成功</returns>
public bool Append(FileInfo localFile, string remoteFileName)
using (FileStream fs = new FileStream(localFile.FullName, FileMode.Open))
return Append(fs, remoteFileName);
/// <param name="stream">資料流(可通過設定偏移來實作從特定位置開始上傳)</param>
public bool Append(Stream stream, string remoteFileName)
if (stream != null && stream.CanRead)
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.AppendFile);
//上傳資料
int count = stream.Read(buffer, 0, buffer.Length);
count = stream.Read(buffer, 0, buffer.Length);
#region 擷取FTP伺服器上的目前路徑
/// 擷取FTP伺服器上的目前路徑
public string CurrentDirectory
string result = string.Empty;
string url = Host.TrimEnd('/') + RemotePath;
FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.PrintWorkingDirectory);
string temp = response.StatusDescription;
int start = temp.IndexOf('"') + 1;
int end = temp.LastIndexOf('"');
if (end >= start)
result = temp.Substring(start, end - start);
#region 檢查目前路徑上是否存在某個檔案
/// 檢查檔案是否存在
/// <param name="fileName">要檢查的檔案名</param>
/// <returns>傳回一個值,訓示要檢查的檔案是否存在</returns>
public bool CheckFileExist(string fileName)
if (fileName != null && fileName.Trim().Length > 0)
fileName = fileName.Trim();
List<string> files = GetFileList();
if (files != null && files.Count > 0)
foreach (string file in files)
if (file.ToLower() == fileName.ToLower())
{
result = true;
break;
}
}
}
/*
FTP全狀态碼查詢詞典
1xx - 肯定的初步答複
這些狀态代碼訓示一項操作已經成功開始,但用戶端希望在繼續操作新指令前得到另一個答複。
本文轉自蓬萊仙羽51CTO部落格,原文連結:http://blog.51cto.com/dingxiaowei/1366854,如需轉載請自行聯系原作者