廢話不多說,直接上代碼
public class FtpHelper
{
private string _ip;
private string _account;
private string _pwd;
public FtpHelper(string ip, string account, string pwd)
{
_ip = ip;
_account = account;
_pwd = pwd;
}
/// <summary>
/// 獲取所有文件(含路徑)
/// </summary>
/// <param name="dir">目錄,可爲空</param>
/// <returns>文件列表</returns>
public List<string> GetFiles(string dir = "")
{
return GetAllFiles("ftp://" + _ip + "/" + dir, dir);
}
/// <summary>
/// 獲取所有文件(含路徑)
/// </summary>
/// <param name="uri">地址:ftp://192.168.0.1/xx/yy/ </param>
/// <param name="deep">子路徑,可爲空</param>
/// <returns>文件列表</returns>
private List<string> GetAllFiles(string uri, string deep)
{
try
{
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftp.Credentials = new NetworkCredential(_account, _pwd);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
List<string> lstResult = new List<string>();
string line = reader.ReadLine();
while (line != null)
{
var arr = line.Split(' ');
string value = arr[arr.Length - 1];
if (line.Contains("<DIR>"))
{
lstResult.AddRange(GetAllFiles(uri + "/" + value, value));
}
else
{
lstResult.Add((deep == "" ? "" : deep + "/") + value);
}
line = reader.ReadLine();
}
reader.Close();
response.Close();
return lstResult;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 獲取所有文件夾
/// </summary>
private List<string> GetAllDirectory(string uri, string deep)
{
try
{
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftp.Credentials = new NetworkCredential(_account, _pwd);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
List<string> lstResult = new List<string>();
string line = reader.ReadLine();
while (line != null)
{
var arr = line.Split(' ');
string value = arr[arr.Length - 1];
if (line.Contains("<DIR>"))
{
lstResult.Add((deep == "" ? "" : deep + "/") + value);
lstResult.AddRange(GetAllDirectory(uri + "/" + value, value));
}
line = reader.ReadLine();
}
reader.Close();
response.Close();
return lstResult;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 判斷文件夾是否存在
/// </summary>
/// <param name="dir">A/B/C</param>
public void CreateFtpDirectory(string dir)
{
if (string.IsNullOrEmpty(dir) == true)
{
return;
}
try
{
bool hasDir = false;
var lstDir = GetAllDirectory("ftp://" + _ip + "/", "");
foreach (string path in lstDir)
{
hasDir = path == (dir.EndsWith("/") ? dir.Substring(0, dir.Length - 1) : dir);
if (hasDir == true)
{
break;
}
}
if (hasDir == false)
{
//判斷不存在,則創建
string uri = "ftp://" + _ip + "/" + (dir.EndsWith("/") ? dir : dir + "/");
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftp.Credentials = new NetworkCredential(_account, _pwd);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 文件上傳
/// </summary>
/// <param name="sourcePath">源文件路徑</param>
/// <param name="savePath">保存路徑</param>
public bool UploadFile(string sourcePath, string savePath)
{
try
{
CreateFtpDirectory(savePath);
FileInfo info = new FileInfo(sourcePath);
string uri = "ftp://" + _ip + "/" + (savePath.EndsWith("/") ? savePath : savePath + "/") + info.Name;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftp.Credentials = new NetworkCredential(_account, _pwd);
ftp.Method = WebRequestMethods.Ftp.UploadFile;
using (Stream rs = ftp.GetRequestStream())
using (FileStream fs = info.OpenRead())
{
byte[] buffer = new byte[2048];
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();
rs.Close();
}
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 下載文件
/// </summary>
/// <param name="lstPath">文件路徑</param>
/// <param name="savePath">保存路徑</param>
public void DownloadFiles(List<string> lstPath, string savePath)
{
try
{
foreach (string path in lstPath)
{
string uri = "ftp://" + _ip + "/" + path;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftp.Credentials = new NetworkCredential(_account, _pwd);
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
Stream stream = response.GetResponseStream();
//沒目錄則創建
if (path.Contains("/") == true)
{
string dirPath = path.Substring(0, path.LastIndexOf("/") + 1);
if (Directory.Exists(savePath + dirPath) == false)
{
Directory.CreateDirectory(savePath + dirPath);
}
}
FileStream fs = new FileStream(savePath + path, FileMode.Create);
byte[] buffer = new byte[2048];
int readCount = stream.Read(buffer, 0, buffer.Length);
while (readCount > 0)
{
fs.Write(buffer, 0, readCount);
readCount = stream.Read(buffer, 0, buffer.Length);
}
stream.Close();
fs.Close();
response.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
以下是調用的代碼
FtpHelper helper = new FtpHelper("192.168.0.1", "test", "test");
var paths = helper.GetFiles();
helper.DownloadFiles(paths, "D:\\FTPTest\\");
helper.UploadFile("D:\\FTPTest\\x.txt", "T3");