1.整理简化了下C#的ftp操作,方便使用

   1.支持创建多级目录

   2.批量删除

   3.整个目录上传

   4.整个目录删除

   5.整个目录下载

2.调用方法展示,

            var ftp = new FtpHelper("10.136.12.11", "qdx1213123", "123ddddf");//初始化ftp,创建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");//创建多级目录

3.FtpHelper 代码。

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

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

3.其他的整个目录操作都是同上

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO; namespace MyStuday
{
/// <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.Magenta.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行成功");
return true;
}
catch (Exception ex)
{
FluentConsole.Red.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败:\n {ex}");
// Logger.Write2File(FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败 \r\n{ex}");
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.Magenta.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行成功");
//Logger.Write2File($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行成功");
return func();
}
catch (Exception ex)
{
//FluentConsole.Red.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败:").Line(ex);
// Logger.Write2File($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执行失败 \r\n{ex}");
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="dirName">目标路径</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 = ;
byte[] buff = new byte[buffLength];
int contentLen;
using (FileStream fs = fileInfo.OpenRead())
{
using (Stream strm = ftp.GetRequestStream())
{
contentLen = fs.Read(buff, , buffLength);
while (contentLen != )
{
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , 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 > - && targIndex != (localDir.IndexOf(":\\") + ))
localDirName = localDir.Substring(, targIndex);
localDirName = localDir.Substring(targIndex + );
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==) return DelDir(dirName);//删除当前目录
var newlist = list.OrderByDescending(x => x.level);
foreach (var item in newlist)
{
FluentConsole.Yellow.Line($@"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("\\") + );
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[];
int read = ;
do
{
read = responseStream.Read(buffer, , buffer.Length);
fs.Write(buffer, , read);
} while (!(read == ));
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 = )
{
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>") > -, name = line.Substring().Trim(), path = Path.Combine(dirName, line.Substring().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 = )
{
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+);
}
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>") > -)
{
if (line.Substring().Trim() == dirName)
return true;
}
line = sr.ReadLine();
}
sr.Close();
}
stream.Close();
return false;
}); } /// </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="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; } = ;
public bool isDir { get; set; }
public string name { get; set; }
public string path { get; set; } = "";
}
}

ftp操作方法整理的更多相关文章

  1. C#开发-ftp操作方法整理

    1.整理简化了下C#的ftp操作,方便使用    1.支持创建多级目录    2.批量删除    3.整个目录上传    4.整个目录删除    5.整个目录下载 2.调用方法展示, var ftp ...

  2. C#开发--FTP操作方法管理

    1.整理简化了下C#的ftp操作,方便使用    1.支持创建多级目录    2.批量删除    3.整个目录上传    4.整个目录删除    5.整个目录下载 2.调用方法展示, var ftp ...

  3. FTP 作业整理

    一.FTP 客户端 与服务器端(没有解决黏包问题的代码) 服务器端设置 import socket import json ADDR = () sk =socket.socket() sk.bind( ...

  4. linux 远程连接服务器ftp命令整理

    Ftp命令的功能是在本地机和远程机之间传送文件.该命令的一般格式如下: $ ftp 主机名/IP ftp将给出提示符,等待用户输入命令: $ ftp ftp > 最常用的命令有: ls 列出远程 ...

  5. 【Fine学习笔记】python 文件l操作方法整理

    python脚本可以对excel进行创建.读.写.保存成指定文件名,保存到指定路径的操作.整理了以下处理方法:   首先区别几个操作方式: "r" 以读方式打开,只能读文件 , 如 ...

  6. [python selenium] 操作方法整理

    个人笔记,摘抄自虫师python selenum,仅供个人参考 1.安装: pip install selenium 下载webdriver # webdriver 下载并放置在python主目录 · ...

  7. vb.net FTP上传下载,目录操作

    https://blog.csdn.net/dzweather/article/details/51429107 FtpWebRequest与FtpWebResponse类用来与特定FTP服务器进行沟 ...

  8. JAVA字符串操作 (转)

    JAVA字符串操作 原帖地址:http://blog.163.com/hn_myj@126/blog/static/50555635200861133942947/ 参考:http://blog.cs ...

  9. C#对.CSV格式的文件--逗号分隔值文件 的读写操作及上传ftp服务器操作方法总结

    前言 公司最近开发需要将数据保存到.csv文件(逗号分隔值 文件)中然后上传到ftp服务器上,供我们系统还有客户系统调用,之前完全没有接触过这个,所以先来看看百度的解释:逗号分隔值(Comma-Sep ...

随机推荐

  1. 32位机,CPU是如何利用段寄存器寻址的

    转自:http://blog.sina.com.cn/s/blog_640531380100xa15.html 32位cpu 地址线扩展成了32位,这和数据线的宽度是一致的.因此,在32位机里其实并不 ...

  2. Oracle 复杂查询(1)

    一.复杂查询 1. 列出至少有一个员工的所有部门编号.名称,并统计出这些部门的平均工资.最低工资.最高工资. 1.确定所需要的数据表: emp表:可以查询出员工的数量: dept表:部门名称: emp ...

  3. Debug 的使用

    R 命令:查看.修改寄存器的内容 -r:查看寄存器的内容 CS=0AF9,IP=0100,也就是说内存 0AF9:0100 处的指令为 CPU 当前要读取.执行的指令 Debug 也列出了 CS:IP ...

  4. [JBPM3.2]TaskNode的signal属性详解

    TaskNode节点的signal属性决定了任务完成时对流程执行继续的影响,共有六种取值:unsynchronized,never,first,first-wait,last,last-wait.默认 ...

  5. 游戏引擎架构Note1

    [游戏引擎架构] 1.第14章介绍的对游戏性相关系统的设计非常有价值.各个开发人员几乎都是凭经验设计,很少见有书籍对这些做总结. 5.通过此书以知悉一些知名游戏作品实际上所采用的方案. 6.书名中的架 ...

  6. 1-5 构建官方example-Windows平台

    https://github.com/facebook/react-native https://github.com/facebook/react-native.git  https://githu ...

  7. 【bzoj1787】[Ahoi2008]Meet 紧急集合

    1787: [Ahoi2008]Meet 紧急集合 Time Limit: 20 Sec  Memory Limit: 162 MBSubmit: 2466  Solved: 1117[Submit] ...

  8. jmeter 插件

  9. Using native JSON

    文介绍了兼容ECMAScript 5 标准的原生JSON对象. 在不支持原生JSON对象的旧版本Firefox中,该如何处理JSON数据.请查看 JSON. 原生JSON对象包含有两个关键方法.JSO ...

  10. Ubuntu无法安装rpm包,ubuntu RPM should not be used directly install RPM packages, use Alien instead!

    Ubuntu无法安装rpm包,ubuntu RPM should not be used directly install RPM packages, use Alien instead! 简单来说, ...