网上找了好多,感觉还是自己这个使用起来方便点,记录一下!
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);
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章