当前位置: 首页 > news >正文

C# .NET FTP上传文件夹操作

#region 上传文件
/// <summary>
/// 上传文件
/// </summary>
/// <param name="localFile">要上传到FTP服务器的文件</param>
/// <param name="ftpPath"></param>
public static void UpLoadFile(string localFile, string ftpPath, string ftpUser, string ftpPassword)
{
if (ftpUser == null)
{
ftpUser = "";
}
if (ftpPassword == null)
{
ftpPassword = "";
}

if (!File.Exists(localFile))
{
MyLog.ShowMessage("文件:“" + localFile + "” 不存在!");
return;
}

FtpWebRequest ftpWebRequest = null;
FileStream localFileStream = null;
Stream requestStream = null;
try
{
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true;
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpWebRequest.ContentLength = localFile.Length;
int buffLength = 4096;
byte[] buff = new byte[buffLength];
int contentLen;
localFileStream = new FileInfo(localFile).OpenRead();
requestStream = ftpWebRequest.GetRequestStream();
contentLen = localFileStream.Read(buff, 0, buffLength);
while (contentLen != 0)
{
requestStream.Write(buff, 0, contentLen);
contentLen = localFileStream.Read(buff, 0, buffLength);
}
}
catch (Exception ex)
{
MyLog.ShowMessage(ex.Message, "FileUpLoad0001");
}
finally
{
if (requestStream != null)
{
requestStream.Close();
}
if (localFileStream != null)
{
localFileStream.Close();
}
}
}
#endregion

#region 上传文件夹
/// <summary>
/// 获取目录下的详细信息
/// </summary>
/// <param name="localDir">本机目录</param>
/// <returns></returns>
private static List<List<string>> GetDirDetails(string localDir)
{
List<List<string>> infos = new List<List<string>>();
try
{
infos.Add(Directory.GetFiles(localDir).ToList()); //获取当前目录的文件

infos.Add(Directory.GetDirectories(localDir).ToList()); //获取当前目录的目录

for (int i = 0; i < infos[0].Count; i++)
{
int index = infos[0][i].LastIndexOf(@"\");
infos[0][i] = infos[0][i].Substring(index + 1);
}
for (int i = 0; i < infos[1].Count; i++)
{
int index = infos[1][i].LastIndexOf(@"\");
infos[1][i] = infos[1][i].Substring(index + 1);
}
}
catch (Exception ex)
{
ex.ToString();
}
return infos;
}

/// <summary>
/// 上传整个目录
/// </summary>
/// <param name="localDir">要上传的目录的上一级目录</param>
/// <param name="ftpPath">FTP路径</param>
/// <param name="dirName">要上传的目录名</param>
/// <param name="ftpUser">FTP用户名(匿名为空)</param>
/// <param name="ftpPassword">FTP登录密码(匿名为空)</param>
public static void UploadDirectory(string localDir, string ftpPath, string dirName, string ftpUser, string ftpPassword)
{
if (ftpUser == null)
{
ftpUser = "";
}
if (ftpPassword == null)
{
ftpPassword = "";
}

string dir = localDir + dirName + @"\"; //获取当前目录(父目录在目录名)

if (!Directory.Exists(dir))
{
MyLog.ShowMessage("目录:“" + dir + "” 不存在!");
return;
}

if (!CheckDirectoryExist(ftpPath,dirName))
{
MakeDir(ftpPath, dirName);
}

List<List<string>> infos = GetDirDetails(dir); //获取当前目录下的所有文件和文件夹

//先上传文件
MyLog.ShowMessage(dir + "下的文件数:" + infos[0].Count.ToString());
for (int i = 0; i < infos[0].Count; i++)
{
Console.WriteLine(infos[0][i]);
UpLoadFile(dir + infos[0][i], ftpPath + dirName + @"/" + infos[0][i], ftpUser, ftpPassword);
}
//再处理文件夹
MyLog.ShowMessage(dir + "下的目录数:" + infos[1].Count.ToString());
for (int i = 0; i < infos[1].Count; i++)
{
UploadDirectory(dir, ftpPath + dirName + @"/", infos[1][i], ftpUser, ftpPassword);
}
}

/// <summary>
/// 新建目录
/// </summary>
/// <param name="ftpPath"></param>
/// <param name="dirName"></param>
public static void MakeDir(string ftpPath, string dirName)
{
try
{
//实例化FTP连接
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + dirName));
//指定FTP操作类型为创建目录
request.Method = WebRequestMethods.Ftp.MakeDirectory;
//获取FTP服务器的响应
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
catch (Exception ex)
{
MyLog.ShowMessage(ex.Message, "MakeDir");
}
}

/// <summary>
/// 检查目录是否存在
/// </summary>
/// <param name="ftpPath">要检查的目录的上一级目录</param>
/// <param name="dirName">要检查的目录名</param>
/// <returns>存在返回true,否则false</returns>
public static bool CheckDirectoryExist(string ftpPath,string dirName)
{
bool result = false;
try
{
//实例化FTP连接
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
//指定FTP操作类型为创建目录
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
//获取FTP服务器的响应
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);

StringBuilder str = new StringBuilder();
string line = sr.ReadLine();
while (line != null)
{
str.Append(line);
str.Append("|");
line = sr.ReadLine();
}
string[] datas = str.ToString().Split('|');

for (int i = 0; i < datas.Length; i++)
{
if (datas[i].Contains("<DIR>"))
{
int index = datas[i].IndexOf("<DIR>");
string name = datas[i].Substring(index + 5).Trim();
if (name==dirName)
{
result = true;
break;
}
}
}

sr.Close();
sr.Dispose();
response.Close();
}
catch (Exception ex)
{
MyLog.ShowMessage(ex.Message, "MakeDir");
}
return result;
}

调用:

//FTP地址
string ftpPath = @"Ftp://192.168.1.68:21/";
//本机要上传的目录的父目录
string localPath = @"D:\";
//要上传的目录名
string fileName = @"haha";
FTPClient.UploadDirectory(localPath, ftpPath, fileName, "", "");

 

 

 

 

相关文章:

  • C# 实现Window服务实现定时发送邮件
  • Access denied for user 'root'@'localhost' (using password:YES) 解决方案
  • Maximum request length exceeded
  • C# 计时器Timer控件,倒计时
  • MySQL 错误Incorrect key file for table ******.MYI; try to repair it的解决
  • 关于无效使用 Null: 'Replace'
  • css透明与半透明
  • C# FTP上传文件至服务器代码
  • 利用FTPClient类实现文件的上传下载功能
  • mysql不能使用innodb存储引擎
  • ASP.NET MVC3 异常处理
  • 解决【Unable to make the session state request to the session state server】
  • 如何在IIS里对网站限速
  • msxml3.dll 错误 '80072efd' A connection with the server could not be established
  • 解决IE6浏览器中Div层挡不住Select组件
  • 【mysql】环境安装、服务启动、密码设置
  • Java超时控制的实现
  • PHP那些事儿
  • Promise初体验
  • python_bomb----数据类型总结
  • React-生命周期杂记
  • 编写符合Python风格的对象
  • 大快搜索数据爬虫技术实例安装教学篇
  • 工程优化暨babel升级小记
  • 如何合理的规划jvm性能调优
  • 如何在 Tornado 中实现 Middleware
  • 学习HTTP相关知识笔记
  • 再谈express与koa的对比
  • 国内唯一,阿里云入选全球区块链云服务报告,领先AWS、Google ...
  • 支付宝花15年解决的这个问题,顶得上做出十个支付宝 ...
  • ​软考-高级-系统架构设计师教程(清华第2版)【第12章 信息系统架构设计理论与实践(P420~465)-思维导图】​
  • #android不同版本废弃api,新api。
  • (2)关于RabbitMq 的 Topic Exchange 主题交换机
  • (4)STL算法之比较
  • (C#)一个最简单的链表类
  • (react踩过的坑)Antd Select(设置了labelInValue)在FormItem中initialValue的问题
  • (附源码)springboot美食分享系统 毕业设计 612231
  • (附源码)ssm捐赠救助系统 毕业设计 060945
  • (数位dp) 算法竞赛入门到进阶 书本题集
  • (四)【Jmeter】 JMeter的界面布局与组件概述
  • (原創) 如何優化ThinkPad X61開機速度? (NB) (ThinkPad) (X61) (OS) (Windows)
  • **PHP二维数组遍历时同时赋值
  • *p++,*(p++),*++p,(*p)++区别?
  • .NET Core 成都线下面基会拉开序幕
  • .NET Standard / dotnet-core / net472 —— .NET 究竟应该如何大小写?
  • .NET Standard、.NET Framework 、.NET Core三者的关系与区别?
  • .Net 知识杂记
  • .NET/C# 异常处理:写一个空的 try 块代码,而把重要代码写到 finally 中(Constrained Execution Regions)
  • .NET构架之我见
  • .NET建议使用的大小写命名原则
  • .NET框架设计—常被忽视的C#设计技巧
  • .secret勒索病毒数据恢复|金蝶、用友、管家婆、OA、速达、ERP等软件数据库恢复
  • ?.的用法
  • [ vulhub漏洞复现篇 ] struts2远程代码执行漏洞 S2-005 (CVE-2010-1870)
  • [android] 天气app布局练习