C#開發(fā)--FTP操作方法管理
當前位置:點晴教程→知識管理交流
→『 技術文檔交流 』
1、整理簡化了下C#的ftp操作,方便使用:
1.支持創(chuàng)建多級目錄
2.批量刪除
3.整個目錄上傳
4.整個目錄刪除
5.整個目錄下載
2、調用方法展示:
var ftp = new FtpHelper("10.136.12.11", "qdx1213123", "123ddddf");//初始化ftp,創(chuàng)建ftp對象
ftp.DelAll("test");//刪除ftptest目錄及其目錄下的所有文件
ftp.UploadAllFile("F:\\test\\wms.zip");//上傳單個文件到指定目錄
ftp.UploadAllFile("F:\\test");//將本地test目錄的所有文件上傳
ftp.DownloadFile("test\\wms.zip", "F:\\test1");//下載單個目錄
ftp.DownloadAllFile("test", "F:\\test1");//批量下載整個目錄
ftp.MakeDir("aaa\\bbb\\ccc\\ddd");//創(chuàng)建多級目錄
3、FtpHelper代碼:
1.異常方法委托,通過Lamda委托統(tǒng)一處理異常,方便改寫。加了個委托方便控制異常輸出;
2.ftp的刪除需要遞歸查找所有目錄存入list,然后根據(jù) level倒序排序,從最末級開始遍歷刪除;
3.其他的整個目錄操作都是同上。
代碼如下: using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
namespace AsyncTcpServer
{
/// <summary>
/// ftp幫助類
/// </summary>
public class FtpHelper
{
private string ftpHostIP { get; set; }
private string username { get; set; }
private string password { get; set; }
private string ftpURI { get { return $@"ftp://{ftpHostIP}/"; } }
/// <summary>
/// 初始化ftp參數(shù)
/// </summary>
/// <param name="ftpHostIP">ftp主機IP</param>
/// <param name="username">ftp賬戶</param>
/// <param name="password">ftp密碼</param>
public FtpHelper(string ftpHostIP, string username, string password)
{
this.ftpHostIP = ftpHostIP;
this.username = username;
this.password = password;
}
/// <summary>
/// 異常方法委托,通過Lamda委托統(tǒng)一處理異常,方便改寫
/// </summary>
/// <param name="method">當前執(zhí)行的方法</param>
/// <param name="action"></param>
/// <returns></returns>
private bool MethodInvoke(string method, Action action)
{
if (action != null)
{
try
{
action();
Console.WriteLine($@"FtpHelper({ftpHostIP},{username},{password}).{method}:執(zhí)行成功");
return true;
}
catch (Exception ex)
{
Console.WriteLine($@"FtpHelper({ftpHostIP},{username},{password}).{method}:執(zhí)行失敗:\n {ex}");
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// 異常方法委托,通過Lamda委托統(tǒng)一處理異常,方便改寫
/// </summary>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="method"></param>
/// <param name="func"></param>
/// <returns></returns>
private T MethodInvoke<T>(string method, Func<T> func)
{
if (func != null)
{
try
{
//Console.WriteLine($@"FtpHelper({ftpHostIP},{username},{password}).{method}:執(zhí)行成功");
return func();
}
catch (Exception ex)
{
//Console.WriteLine($@"FtpHelper({ftpHostIP},{username},{password}).{method}:執(zhí)行失敗:").Line(ex);
return default(T);
}
}
else
{
return default(T);
}
}
private FtpWebRequest GetRequest(string URI)
{
//根據(jù)服務器信息FtpWebRequest創(chuàng)建類的對象
FtpWebRequest result = (FtpWebRequest)WebRequest.Create(URI);
result.Credentials = new NetworkCredential(username, password);
result.KeepAlive = false;
result.UsePassive = false;
result.UseBinary = true;
return result;
}
/// <summary> 上傳文件</summary>
/// <param name="filePath">需要上傳的文件路徑</param>
/// <param name="dirName">目標路徑</param>
public bool UploadFile(string filePath, string dirName = "")
{
FileInfo fileInfo = new FileInfo(filePath);
if (dirName != "") MakeDir(dirName);//檢查文件目錄,不存在就自動創(chuàng)建
string uri = Path.Combine(ftpURI, dirName, fileInfo.Name);
return MethodInvoke($@"uploadFile({filePath},{dirName})", () =>
{
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.UploadFile;
ftp.ContentLength = fileInfo.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
using (FileStream fs = fileInfo.OpenRead())
{
using (Stream strm = ftp.GetRequestStream())
{
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
}
fs.Close();
}
});
}
/// <summary>
/// 從一個目錄將其內容復制到另一目錄
/// </summary>
/// <param name="localDir">源目錄</param>
/// <param name="DirName">目標目錄</param>
public void UploadAllFile(string localDir, string DirName = "")
{
string localDirName = string.Empty;
int targIndex = localDir.LastIndexOf("\\");
if (targIndex > -1 && targIndex != (localDir.IndexOf(":\\") + 1))
localDirName = localDir.Substring(0, targIndex);
localDirName = localDir.Substring(targIndex + 1);
string newDir = Path.Combine(DirName, localDirName);
MethodInvoke($@"UploadAllFile({localDir},{DirName})", () =>
{
MakeDir(newDir);
DirectoryInfo directoryInfo = new DirectoryInfo(localDir);
FileInfo[] files = directoryInfo.GetFiles();
//復制所有文件
foreach (FileInfo file in files)
{
UploadFile(file.FullName, newDir);
}
//最后復制目錄
DirectoryInfo[] directoryInfoArray = directoryInfo.GetDirectories();
foreach (DirectoryInfo dir in directoryInfoArray)
{
UploadAllFile(Path.Combine(localDir, dir.Name), newDir);
}
});
}
/// <summary>
/// 刪除單個文件
/// </summary>
/// <param name="filePath"></param>
public bool DelFile(string filePath)
{
string uri = Path.Combine(ftpURI, filePath);
return MethodInvoke($@"DelFile({filePath})", () =>
{
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
});
}
/// <summary>
/// 刪除最末及空目錄
/// </summary>
/// <param name="dirName"></param>
private bool DelDir(string dirName)
{
string uri = Path.Combine(ftpURI, dirName);
return MethodInvoke($@"DelDir({dirName})", () =>
{
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
});
}
/// <summary> 刪除目錄或者其目錄下所有的文件 </summary>
/// <param name="dirName">目錄名稱</param>
/// <param name="ifDelSub">是否刪除目錄下所有的文件</param>
public bool DelAll(string dirName)
{
var list = GetAllFtpFile(new List<ActFile>(), dirName);
if (list == null) return DelDir(dirName);
if (list.Count == 0) return DelDir(dirName);//刪除當前目錄
var newlist = list.OrderByDescending(x => x.level);
foreach (var item in newlist)
{
Console.WriteLine($@"level:{item.level},isDir:{item.isDir},path:{item.path}");
}
string uri = Path.Combine(ftpURI, dirName);
return MethodInvoke($@"DelAll({dirName})", () =>
{
foreach (var item in newlist)
{
if (item.isDir)//判斷是目錄調用目錄的刪除方法
DelDir(item.path);
else
DelFile(item.path);
}
DelDir(dirName);//刪除當前目錄
return true;
});
}
/// <summary>
/// 下載單個文件
/// </summary>
/// <param name="ftpFilePath">從ftp要下載的文件路徑</param>
/// <param name="localDir">下載至本地路徑</param>
/// <param name="filename">文件名</param>
public bool DownloadFile(string ftpFilePath, string saveDir)
{
string filename = ftpFilePath.Substring(ftpFilePath.LastIndexOf("\\") + 1);
string tmpname = Guid.NewGuid().ToString();
string uri = Path.Combine(ftpURI, ftpFilePath);
return MethodInvoke($@"DownloadFile({ftpFilePath},{saveDir},{filename})", () =>
{
if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (FileStream fs = new FileStream(Path.Combine(saveDir, filename), FileMode.CreateNew))
{
byte[] buffer = new byte[2048];
int read = 0;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
} while (!(read == 0));
responseStream.Close();
fs.Flush();
fs.Close();
}
responseStream.Close();
}
response.Close();
}
});
}
/// <summary>
/// 從FTP下載整個文件夾
/// </summary>
/// <param name="dirName">FTP文件夾路徑</param>
/// <param name="saveDir">保存的本地文件夾路徑</param>
public void DownloadAllFile(string dirName, string saveDir)
{
MethodInvoke($@"DownloadAllFile({dirName},{saveDir})", () =>
{
List<ActFile> files = GetFtpFile(dirName);
if (!Directory.Exists(saveDir))
{
Directory.CreateDirectory(saveDir);
}
foreach (var f in files)
{
if (f.isDir) //文件夾,遞歸查詢
{
DownloadAllFile(Path.Combine(dirName, f.name), Path.Combine(saveDir, f.name));
}
else //文件,直接下載
{
DownloadFile(Path.Combine(dirName, f.name), saveDir);
}
}
});
}
/// <summary>
/// 獲取當前目錄下的目錄及文件
/// </summary>
/// param name="ftpfileList"></param>
/// <param name="dirName"></param>
/// <returns></returns>
public List<ActFile> GetFtpFile(string dirName, int ilevel = 0)
{
var ftpfileList = new List<ActFile>();
string uri = Path.Combine(ftpURI, dirName);
return MethodInvoke($@"GetFtpFile({dirName})", () =>
{
var a = new List<List<string>>();
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
Stream stream = ftp.GetResponse().GetResponseStream();
using (StreamReader sr = new StreamReader(stream))
{
string line = sr.ReadLine();
while (!string.IsNullOrEmpty(line))
{
ftpfileList.Add(new ActFile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(), path = Path.Combine(dirName, line.Substring(39).Trim()), level = ilevel });
line = sr.ReadLine();
}
sr.Close();
}
return ftpfileList;
});
}
/// <summary>
/// 獲取FTP目錄下的所有目錄及文件包括其子目錄和子文件
/// </summary>
/// param name="result"></param>
/// <param name="dirName"></param>
/// <returns></returns>
public List<ActFile> GetAllFtpFile(List<ActFile> result, string dirName, int level = 0)
{
var ftpfileList = new List<ActFile>();
string uri = Path.Combine(ftpURI, dirName);
return MethodInvoke($@"GetAllFtpFile({dirName})", () =>
{
ftpfileList = GetFtpFile(dirName, level);
result.AddRange(ftpfileList);
var newlist = ftpfileList.Where(x => x.isDir).ToList();
foreach (var item in newlist)
{
GetAllFtpFile(result, item.path, level + 1);
}
return result;
});
}
/// <summary>
/// 檢查目錄是否存在
/// </summary>
/// <param name="dirName"></param>
/// <param name="currentDir"></param>
/// <returns></returns>
public bool CheckDir(string dirName, string currentDir = "")
{
string uri = Path.Combine(ftpURI, currentDir);
return MethodInvoke($@"CheckDir({dirName}{currentDir})", () =>
{
FtpWebRequest ftp = GetRequest(uri);
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
Stream stream = ftp.GetResponse().GetResponseStream();
using (StreamReader sr = new StreamReader(stream))
{
string line = sr.ReadLine();
while (!string.IsNullOrEmpty(line))
{
if (line.IndexOf("<DIR>") > -1)
{
if (line.Substring(39).Trim() == dirName)
return true;
}
line = sr.ReadLine();
}
sr.Close();
}
stream.Close();
return false;
});
}
/// </summary>
/// 在ftp服務器上創(chuàng)建指定目錄,父目錄不存在則創(chuàng)建
/// </summary>
/// <param name="dirName">創(chuàng)建的目錄名稱</param>
public bool MakeDir(string dirName)
{
var dirs = dirName.Split('\\').ToList();//針對多級目錄分割
string currentDir = string.Empty;
return MethodInvoke($@"MakeDir({dirName})", () =>
{
foreach (var dir in dirs)
{
if (!CheckDir(dir, currentDir))//檢查目錄不存在則創(chuàng)建
{
currentDir = Path.Combine(currentDir, dir);
string uri = Path.Combine(ftpURI, currentDir);
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
else
{
currentDir = Path.Combine(currentDir, dir);
}
}
});
}
/// <summary>文件重命名 </summary>
/// <param name="currentFilename">當前名稱</param>
/// <param name="newFilename">重命名名稱</param>
/// <param name="currentFilename">所在的目錄</param>
public bool Rename(string currentFilename, string newFilename, string dirName = "")
{
string uri = Path.Combine(ftpURI, dirName, currentFilename);
return MethodInvoke($@"Rename({currentFilename},{newFilename},{dirName})", () =>
{
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.Rename;
ftp.RenameTo = newFilename;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
});
}
}
public class ActFile
{
public int level { get; set; } = 0;
public bool isDir { get; set; }
public string name { get; set; }
public string path { get; set; } = "";
}
} 該文章在 2021/7/7 16:14:36 編輯過 |
關鍵字查詢
相關文章
正在查詢... |