C#开发教程之ftp操作方法整理

 更新时间:2016年07月26日 11:12:28   作者:costyuan  
这篇文章主要介绍了C#开发教程之ftp操作方法整理的相关资料,需要的朋友可以参考下

1.最近项目开发涉及到ftp操作。发现FtpWebRequest类有些操作很麻烦,

例如创建目录只能创建一级目录,多级就失败。删除目录只能删除最后一级的空目录。同样下载也是。

故写下帮助类方便使用。

2.调用方法展示,

var ftp = new FtpHelper("111.111.111.111", "xxxxxxx", "xxxxxx");//初始化ftp,创建ftp对象
ftp.uploadFile("F:\\wms.zip","aaa//bbb");//参数1本地文件,参数2:ftp的目录
ftp.delDirAll("aaa");//参数 要删除的目录的 路径
ftp.downloadAllFile("aaa","F:\\myfile");//参数1:要下载的目录,参数2,保存到本地的目录

3.FtpHelper 代码。后续再补充说明

1.异常方法委托,通过Lamda委托统一处理异常,方便改写。加了个委托方便控制异常输出

2.递归查找所有目录存入list,然后根据 level排序,从最末级开始遍历删除

3.ftp的目录列表比较怪,暂时用截取字符串的获取 目录或文件

/// <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参数
/// </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委托统一处理异常,方便改写
/// </summary>
/// <param name="method">当前执行的方法</param>
/// <param name="action"></param>
/// <returns></returns>
private bool MethodInvoke(string method, Action action)
{
if (action != null)
{
try
{
action();
//Logger.Write2File($@"FtpHelper.{method}:执行成功");
FluentConsole.Red.Line($@"FtpHelper.{method}:执行成功");
return true;
}
catch (Exception ex)
{
FluentConsole.Red.Line($@"FtpHelper.{method}:执行失败", ex.ToString());
// Logger.Write2File(action.GetType().Name, ex.ToString());
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// 异常方法委托,通过Lamda委托统一处理异常,方便改写
/// </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
{
FluentConsole.Red.Line($@"FtpHelper.{method}:执行成功");
return func();
//Logger.Write2File($@"FtpHelper.{method}:执行成功");
}
catch (Exception ex)
{
FluentConsole.Red.Line($@"FtpHelper.{method}:执行失败:{ex}");
// Logger.Write2File($@"FtpHelper.{method}:执行失败", ex.ToString());
return default(T);
}
}
else
{
return default(T);
}
}
private FtpWebRequest GetRequest(string URI)
{
//根据服务器信息FtpWebRequest创建类的对象
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="targetDir">目标路径</param>
public bool uploadFile(string filePath, string dirName = "")
{
FileInfo fileInfo = new FileInfo(filePath);
if (dirName != "") makeDir(dirName);
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="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))
{
string dir = string.Empty;
if (line.IndexOf("<DIR>") > -1)
{
if (line.Substring(line.IndexOf("<DIR>") + 5).Trim() == dirName)
return true;
}
line = sr.ReadLine();
}
sr.Close();
}
stream.Close();
return false;
});
}
/// <summary>
/// 获取当前目录下的目录及文件
/// </summary>
/// param name="ftpfileList"></param>
/// <param name="dirName"></param>
/// <returns></returns>
public List<Ftpfile> getFtpFile(string dirName)
{
var ftpfileList = new List<Ftpfile>();
string uri = Path.Combine(ftpURI, dirName);
return MethodInvoke($@"getFile({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 Ftpfile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(),path= Path.Combine(dirName, line.Substring(39).Trim()) });
line = sr.ReadLine();
}
sr.Close();
}
return ftpfileList;
});
}
/// <summary>
/// 获取目录下的所有目录及文件包括其子目录和子文件
/// </summary>
/// param name="ftpfileList"></param>
/// <param name="dirName"></param>
/// <returns></returns>
public List<Ftpfile> getAllFtpFile(List<Ftpfile> ftpfileList, string dirName, int level = 0)
{
var flist = new List<Ftpfile>();
string uri = Path.Combine(ftpURI, dirName);
return MethodInvoke($@"getFile({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))
{
flist.Add(new Ftpfile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(), level = level, path= Path.Combine(dirName ,line.Substring(39).Trim()) });
ftpfileList.Add(new Ftpfile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(), level = level, path = Path.Combine(dirName, line.Substring(39).Trim()) });
line = sr.ReadLine();
}
sr.Close();
}
var nflist = flist.Where(x => x.isDir).ToList();
if (nflist.Count == 0)
return ftpfileList;
else
return getAllFtpFile(ftpfileList, Path.Combine(dirName, nflist.First().name), level + 1);
});
}
/// </summary>
/// 在ftp服务器上创建指定目录,父目录不存在则创建
/// </summary>
/// <param name="dirName">创建的目录名称</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))//检查目录不存在则创建
{
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="filePath"></param>
public bool delFile(string filePath)
{
string uri = Path.Combine(ftpURI, filePath);
return MethodInvoke($@"deleteFile({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 void delDirAll(string dirName)
{
var dlist = getAllFtpFile(new List<Ftpfile>(),dirName);
dlist.OrderByDescending(x => x.level);//降序排列,先删除末及文件或空目录
string uri = Path.Combine(ftpURI, dirName);
MethodInvoke($@"delDirAll({dirName})", () =>
{
foreach (var item in dlist)
{
if (item.isDir)//判断是目录调用目录的删除方法
delDir(item.path);
else
delFile(item.path);
}
});
}
/// <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();
});
}
/// <summary>
/// 下载单个文件
/// </summary>
/// <param name="ftpFilePath">从ftp要下载的文件路径</param>
/// <param name="localDir">下载至本地路径</param>
/// <param name="filename">文件名</param>
public bool downloadFile(string ftpFilePath, string saveDir, string filename)
{
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<Ftpfile> 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, f.name);
}
}
});
}
}
public class Ftpfile
{
public int level { get; set; } = 0;
public bool isDir { get; set; }
public string name { get; set; }
public string path { get; set; } = "";
}

以上所述是小编给大家介绍的C#开发教程之ftp操作方法整理,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

最新评论