FtpHelper.cs
网上找了好多,感觉还是自己这个使用起来方便点,记录一下!
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Net;
using System.Text; namespace FtpTest.Common
{ public class FtpHelper
{
private readonly string _ftpUri; //ftp服务器地址
private readonly string _ftpName; //ftp帐户
private readonly string _ftpPwd; //ftp密码
private FtpWebRequest _ftpRequest; //请求
private FtpWebResponse _ftpResponse; //响应 public FtpHelper(string uri, string name, string password)
{
_ftpUri = uri;
_ftpName = name;
_ftpPwd = password;
} /// <summary>
/// 连接类
/// </summary>
/// <param name="uri">ftp地址</param>
private void Conn(string uri)
{
_ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
//登录ftp服务器,ftpName:账户名,ftpPwd:密码
_ftpRequest.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
_ftpRequest.UseBinary = true; //该值指定文件传输的数据类型。
} /// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName">文件名</param>
public void DeleteFileName(string fileName)
{
string uri = _ftpUri + "/" + fileName;
Conn(uri);
try
{
_ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
_ftpResponse.Close();
}
catch (Exception)
{
// ignored
}
} /// <summary>
/// 删除ftp上目录
/// </summary>
/// <param name="dirName"></param>
public void RemoveDir(string dirName)
{
string uri = _ftpUri + "/" + dirName;
Conn(uri);
try
{
_ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
_ftpResponse.Close();
}
catch (Exception)
{
// ignored
}
} /// <summary>
/// 上传文件,使用FTPWebRequest、FTPWebResponse实例
/// </summary>
/// <param name="uri">ftp地址</param>
/// <param name="fileName">文件名</param>
/// <param name="fileData">文件内容</param>
/// <param name="msg">传出参数,返回传输结果</param>
public void UploadFile(string uri, string fileName, byte[] fileData, out string msg)
{
string ftpUri = uri.EndsWith("/") ? uri : uri + "/";
ftpUri += fileName;
//连接ftp服务器
Conn(ftpUri);
_ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
_ftpRequest.ContentLength = fileData.Length; //上传文件时通知服务器文件的大小
try
{
//将文件流中的数据(byte[] fileData)写入请求流
using (Stream ftpstream = _ftpRequest.GetRequestStream())
{
ftpstream.Write(fileData, , fileData.Length);
} _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse(); //响应
msg = _ftpResponse.StatusDescription; //响应状态
_ftpResponse.Close();
}
catch (Exception exp)
{
msg = "Failed to upload:" + exp.Message;
}
} /// <summary>
/// 上传文件,使用WebClient类
/// </summary>
/// <param name="uri">ftp地址</param>
/// <param name="fileName">文件名</param>
/// <param name="fileData">文件内容</param>
/// <param name="msg">传出参数,输出传输结果</param>
public void UploadFileByWebClient(string uri, string fileName, byte[] fileData, out string msg)
{
string ftpUri = uri.EndsWith("/") ? uri : uri + "/";
ftpUri += fileName; try
{
WebClient client = new WebClient { Credentials = new NetworkCredential(_ftpName, _ftpPwd) };
//登录FTP服务
client.UploadData(ftpUri, "STOR", fileData); //指定为ftp上传方式
msg = "上传成功!";
}
catch (Exception exp)
{
msg = "Failed to upload:" + exp.Message;
}
} /// <summary>
/// 下载文件,使用FTPWebRequest、FTPWebResponse实例
/// </summary>
/// <param name="uri">ftp地址</param>
/// <param name="destinationDir">目标文件存放地址</param>
/// <param name="msg">传出参数,返回传输结果</param>
public void DownloadFile(string uri, string destinationDir, out string msg)
{
string fileName = Path.GetFileName(uri);
// ReSharper disable once AssignNullToNotNullAttribute
string destinationPath = Path.Combine(destinationDir, fileName); try
{
//连接ftp服务器
Conn(uri); using (FileStream outputStream = new FileStream(destinationPath, FileMode.OpenOrCreate))
{
using (_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse())
{
//将响应流中的数据写入到文件流
using (Stream ftpStream = _ftpResponse.GetResponseStream())
{
int bufferSize = ;
byte[] buffer = new byte[bufferSize];
if (ftpStream != null)
{
var readCount = ftpStream.Read(buffer, , bufferSize);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpStream.Read(buffer, , bufferSize);
}
}
}
msg = _ftpResponse.StatusDescription;
}
}
}
catch (Exception exp)
{
msg = "Failed to download:" + exp.Message;
}
} public byte[] DownloadFile()
{
try
{
WebClient client = new WebClient { Credentials = new NetworkCredential(_ftpName, _ftpPwd) };
byte[] responseData = client.DownloadData(_ftpUri);
return responseData;
}
catch (Exception ex)
{
// ReSharper disable once PossibleIntendedRethrow
throw ex;
}
} /// <summary>
/// 文件下载,使用WebClient类
/// </summary>
/// <param name="uri">ftp服务地址</param>
/// <param name="destinationDir">存放目录</param>
public void DownloadFileByWebClient(string uri, string destinationDir)
{
string fileName = Path.GetFileName(uri);
// ReSharper disable once AssignNullToNotNullAttribute
string destinationPath = Path.Combine(destinationDir, fileName); try
{
WebClient client = new WebClient { Credentials = new NetworkCredential(_ftpName, _ftpPwd) }; byte[] responseData = client.DownloadData(uri); using (FileStream fileStream = new FileStream(destinationPath, FileMode.OpenOrCreate))
{
fileStream.Write(responseData, , responseData.Length);
}
}
catch (Exception)
{
// ignored
}
} /// <summary>
/// 遍历文件
/// </summary>
public ArrayList GetListDirectoryDetails()
{
ArrayList fileInfo = new ArrayList();
try
{
Conn(_ftpUri); //获取 FTP 服务器上的文件的详细列表的 FTP LIST 协议方法
_ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse(); //响应
}
catch (WebException)
{
}
catch (InvalidOperationException)
{
} using (Stream responseStream = _ftpResponse.GetResponseStream())
{
// ReSharper disable once AssignNullToNotNullAttribute
using (StreamReader reader = new StreamReader(responseStream))
{
string line = reader.ReadLine();
while (line != null)
{
fileInfo.Add(line);
line = reader.ReadLine();
}
}
}
}
catch (Exception)
{
// ignored
} return fileInfo;
} /// <summary>
/// 上传图片
/// </summary>
/// <param name="mstr"></param>
/// <param name="ftpUri"></param>
/// <returns></returns>
public bool Upload(MemoryStream mstr, string ftpUri)
{
try
{
FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri);
ftp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
ftp.Method = WebRequestMethods.Ftp.UploadFile;
ftp.UseBinary = true;
ftp.UsePassive = true;
using (Stream stream = ftp.GetRequestStream())
{
byte[] bytes = mstr.ToArray();
stream.Write(bytes, , bytes.Length);
stream.Close();
mstr.Close();
}
return true;
}
catch (Exception)
{
return false;
}
} public bool Upload(byte[] mstr, string ftpUri)
{
try
{
FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri);
ftp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
ftp.Method = WebRequestMethods.Ftp.UploadFile;
ftp.UseBinary = true;
ftp.UsePassive = true;
using (Stream stream = ftp.GetRequestStream())
{
stream.Write(mstr, , mstr.Length);
stream.Close();
}
return true;
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 重命名文件
/// </summary>
/// <param name="fileName">原文件名</param>
/// <param name="reNameFileName">新文件名</param>
public bool RenameFileName(string fileName, string reNameFileName)
{
bool result = true;
FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(reNameFileName);
ftp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
try
{
ftp.Method = WebRequestMethods.Ftp.Rename;
ftp.RenameTo = fileName;
ftp.UseBinary = true;
ftp.UsePassive = true;
_ftpResponse = (FtpWebResponse)ftp.GetResponse();
Stream ftpStream = _ftpResponse.GetResponseStream();
// ReSharper disable once PossibleNullReferenceException
ftpStream.Close();
_ftpResponse.Close();
}
catch (Exception)
{
result = false;
} return result;
} /// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName">文件名</param>
public bool DeleteFile(string fileName)
{
bool result = true;
FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(fileName);
ftp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
try
{
ftp.Method = WebRequestMethods.Ftp.DeleteFile;
ftp.UseBinary = true;
ftp.UsePassive = true;
_ftpResponse = (FtpWebResponse)ftp.GetResponse();
Stream ftpStream = _ftpResponse.GetResponseStream();
// ReSharper disable once PossibleNullReferenceException
ftpStream.Close();
_ftpResponse.Close();
}
catch (Exception)
{
result = false;
} return result;
} /// <summary>
/// 创建目录
/// </summary>
/// <param name="dri"></param>
/// <returns></returns>
public bool FtpMakeDir(string dri)
{
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(dri);
req.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
req.Method = WebRequestMethods.Ftp.MakeDirectory;
try
{
FtpWebResponse response = (FtpWebResponse)req.GetResponse();
response.Close();
}
catch (Exception)
{
req.Abort();
return false;
}
req.Abort();
return true;
} /// <summary>
/// 创建多级目录
/// </summary>
/// <param name="ftppath">目录,例如:/aaa/bbb/ccc </param>
public bool FtpMakeDirs(string ftppath)
{
string targetPath = _ftpUri;
var pathArray = ftppath.Split('/'); try
{
//遍历判断文件夹是否存在
foreach (var path in pathArray)
{
if (!string.IsNullOrEmpty(path.Trim()))
{
//不存在此层文件夹
if (!DirectoryExist(targetPath, path))
FtpMakeDir(targetPath + "/" + path); targetPath += "/" + path;
}
}
}
catch (Exception)
{
return false;
} return true;
} /// <summary>
/// 下载
/// </summary>
/// <param name="fileName"></param>
public byte[] Download(string fileName)
{
byte[] buffer = null;
try
{
// ReSharper disable once AccessToStaticMemberViaDerivedType
var reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri + "/" + fileName));
reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
Stream ftpStream = response.GetResponseStream();
int bufferSize = ; //Convert.ToInt32(GetFileSize(fileName)) + 51200;//
buffer = new byte[bufferSize];
// ReSharper disable once PossibleNullReferenceException
var readCount = ftpStream.Read(buffer, , bufferSize); while (readCount > )
{
readCount = ftpStream.Read(buffer, , bufferSize);
}
ftpStream.Close();
response.Close();
}
catch (Exception)
{
// ignored
} return buffer;
} /// <summary>
/// 获取当前目录下明细(包含文件和文件夹)
/// </summary>
/// <returns></returns>
public string[] GetFilesDetailList(string targetPath)
{
var tempftpUri = targetPath; try
{
StringBuilder result = new StringBuilder(); Conn(tempftpUri);
//获取 FTP 服务器上的文件的详细列表的 FTP LIST 协议方法
_ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = _ftpRequest.GetResponse();
// ReSharper disable once AssignNullToNotNullAttribute
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine(); while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
} result.Remove(result.ToString().LastIndexOf("\n", StringComparison.Ordinal), );
reader.Close();
response.Close(); return result.ToString().Split('\n');
}
catch (Exception)
{
var downloadFiles = new string[] { };
return downloadFiles;
}
} /// <summary>
/// 获取当前目录下所有的文件夹列表(仅文件夹)
/// </summary>
/// <returns></returns>
public string[] GetDirectoryList(string targetPath)
{
string[] drectory = GetFilesDetailList(targetPath);
string m = "";
if (drectory != null && true & drectory.Any())
{
foreach (string str in drectory)
{
int dirPos = str.IndexOf("<DIR>", StringComparison.Ordinal);
if (dirPos > )
{
/*判断 Windows 风格*/
m += str.Substring(dirPos + ).Trim() + "\n";
}
else if (str.Trim().Substring(, ).ToUpper() == "D")
{
/*判断 Unix 风格*/
string dir = str.Substring().Trim();
if (dir != "." && dir != "..")
{
m += dir + "\n";
}
}
}
}
char[] n = new char[] { '\n' };
return m.Split(n);
} /// <summary>
/// 判断当前目录下指定的子目录是否存在
/// modified at 2015/4/7 修改判断是否存在的方法,以前的方式过于臃肿,还有bug(竟然使用listdetail!)
/// </summary>
/// <param name="targetPath">服务器地址</param>
/// <param name="remoteDirectoryName">指定的目录名</param>
public bool DirectoryExist(string targetPath, string remoteDirectoryName)
{
try
{
var uri = Path.Combine(targetPath, remoteDirectoryName).Replace(@"\", @"/");
Conn(uri);
_ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; using (var response = (FtpWebResponse)_ftpRequest.GetResponse())
// ReSharper disable once AssignNullToNotNullAttribute
// ReSharper disable once UnusedVariable
using (var stream = new StreamReader(response.GetResponseStream()))
{
}
return true;
}
catch (Exception)
{
// ignored
} return false;
} /// <summary>
/// 获取指定文件大小
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public long GetFileSize(string filename)
{
long fileSize = ;
try
{
// ReSharper disable once AccessToStaticMemberViaDerivedType
var reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri + "/" + filename)); reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(_ftpName, _ftpPwd); FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength; // ReSharper disable once PossibleNullReferenceException
ftpStream.Close();
response.Close();
}
catch (Exception)
{
// ignored
} return fileSize;
} /// <summary>
/// 获取当前目录下文件列表(仅文件)
/// </summary>
/// <returns></returns>
public string[] GetFileList(string mask)
{
StringBuilder result = new StringBuilder();
try
{
// ReSharper disable once AccessToStaticMemberViaDerivedType
var reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(_ftpName, _ftpPwd);
reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFtp.GetResponse();
// ReSharper disable once AssignNullToNotNullAttribute
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); string line = reader.ReadLine();
while (line != null)
{
if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
{
var masks = mask.Substring(, mask.IndexOf("*", StringComparison.Ordinal));
if (line.Substring(, masks.Length) == masks)
{
result.Append(line);
result.Append("\n");
}
}
else
{
result.Append(line);
result.Append("\n");
}
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), );
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。")
{
}
return null;
}
} /// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool FileExist(string filename)
{
bool result;
WebResponse response = null;
try
{
WebRequest req = WebRequest.Create(filename);
response = req.GetResponse();
result = true;
}
catch (Exception)
{
result = false;
}
finally
{
response?.Close();
} return result;
}
}
}
Test:
1、创建多级目录:
string targetPath = "ftp://192.168.1.148/";
string ftpUserName = "ftpuser";
string ftpPassword = ""; var path = "1234/1234/1234";
FtpHelper ftpHelper = new FtpHelper(targetPath , ftpUserName, ftpPassword);
try
{
ftpHelper.FtpMakeDirs(path);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
FtpHelper.cs的更多相关文章
- C# 利用FTP自动下载xml文件后利用 FileSystemWatcher 监控目录下文件变化并自动更新数据库
using FtpLib; using System; using System.Collections.Generic; using System.ComponentModel; using Sys ...
- [C#] 剖析 AssemblyInfo.cs - 了解常用的特性 Attribute
剖析 AssemblyInfo.cs - 了解常用的特性 Attribute [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/5944391.html 序 ...
- Atitit 软件架构方法的进化与演进cs bs soa roa msa attilax总结
Atitit 软件架构方法的进化与演进cs bs soa roa msa attilax总结 1.1. 软件体系架构是沿着单机到 CS 架构,再到 BS 的三层架构甚至多层架构逐步发展过来的,关于 ...
- 从java文件和CS文件里查询方法使用次数工具
前几天,领导让我找一下老系统(Java)里getRemoteUser方法都哪个文件用了,package是什么,方法被调用了多少次,当时因为着急,所以,直接人工找的,但是以后要是再出现,人工找就太讨厌了 ...
- 关于 WP 开发中.xaml 与.xaml.cs 的关系
今天我们先来看一下在WP8.1开发中最长见到的几个文件之间的关系.比较论证,在看这个问题之前我们简单看看.NET平台其他两个不同的框架: Windows Forms 先看看Window Forms中的 ...
- .net 用户控件ascx.cs注册js脚本代码无效果
在.net web项目中碰到一个比较奇怪的问题,网上没找到解决方案,先自己mark一下 问题描述: 添加一个用户控件ascx,在后端.cs添加js注册脚本,执行后没有弹出框 注册脚本为: this.P ...
- DateHelper.cs日期时间操作辅助类C#
//==================================================================== //** Copyright © classbao.com ...
- 仅用aspx文件实现Ajax调用后台cs程序。(实例)
仅用aspx文件实现Ajax调用后台cs无刷新程序.(实例) 两个文件:aaa.aspx 和aaa.aspx.cs 一.aaa.aspx <script type="text/java ...
- Etw EventSourceProvider_EventsProducer.cs OopConsoleTraceEventListenerMonitor_TraceControllerEventsConsumer.cs
// EventSourceProvider_EventsProducer.cs /* /r:"D:\Microshaoft.Nuget.Packages\Microsoft.Diagnos ...
随机推荐
- AOP的应用与基本概念(源自别人的博文)
什么是AOP AOP(Aspect-OrientedProgramming,面向方面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP引入 ...
- Git安装使用秘籍
首先Git的功能,是用于帮助用户实现版本控制的软件,GIT一般和GitHub配套使用.Git是个软件,GitHub是个网站,它们的关系就像雷锋与雷峰塔一样,没什么关系.本文只提供Git安装方法,其它请 ...
- [Tarjan系列] 无向图e-DCC和v-DCC的缩点
上一篇讲了如何应用Tarjan算法求出e-DCC和v-DCC. 那么这一篇就是e-DCC和v-DCC的应用之一:缩点. 先讲e-DCC的缩点. 我们把每一个e-DCC都看成一个节点,把所有桥边(x,y ...
- vue中$router 与 $route区别
vue-router中经常会操作的两个对象\(route和\)router两个. 1.$route对象 $route对象表示当前的路由信息,包含了当前 URL 解析得到的信息.包含当前的路径,参数,q ...
- C# Extension Methods(C#类方法扩展)
使用Extension methods 可以在已有的类型(types)中添加方法(Methods),而无需通过增加一种新的类型或修改已有的类型. 比如说,想要给string类型增加一个PrintStr ...
- kubernetes 集群内部访问外部的数据库endpoint
k8s访问集群外独立的服务最好的方式是采用Endpoint方式,以mysql服务为例: 创建mysql-service.yaml apiVersion: v1 kind: Service metada ...
- css对应rgb码表16进制
- 编写Dockerfile自定义镜像
要求 编写一个Dockerfile自定义centos镜像,要求在容器内部可以使用vim和ifconfig命令,并且登入落脚点为/usr/local 编写Dockerfile FROM centos M ...
- for in和for of的区别
for in:一般用于遍历普通对象(即没有部署Iterator接口),遍历的是属性. for of:ES6新增的遍历方式,能遍历大部分的类型,遍历的是值.for...of 允许你遍历 Arrays(数 ...
- # 机器学习算法总结-第六天(Adaboost算法)
SKlearn中的Adaboost使用 主要调的参数:第一部分是对我们的Adaboost的框架进行调参, 第二部分是对我们选择的弱分类器进行调参. 使用 Adaboost 进行手写数字识别 导入库,载 ...