1.FTP文件操作类   FtpClient

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Xml.Serialization;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Linq; namespace XMDD.NewWeb
{
public class FtpClient
{
private string _ftpServerIp;
private string _ftpRemotePath; public string FtpRemotePath
{
get { return _ftpRemotePath; }
set
{
_ftpRemotePath = value;
if (!string.IsNullOrWhiteSpace(_ftpRemotePath))
this._ftpUri = "ftp://" + _ftpServerIp + "/" + _ftpRemotePath + "/";
else
this._ftpUri = "ftp://" + _ftpServerIp + "/";
}
}
private string _ftpUserId;
private string _ftpPassword;
private string _localSavePath;
private string _ftpUri; public void InitFtp(string ftpServerIp, string ftpRemotePath, string ftpUserId, string ftpPassword, string localSavePath)
{
this._ftpServerIp = ftpServerIp;
this._ftpUserId = ftpUserId;
this._ftpPassword = ftpPassword;
this._localSavePath = localSavePath; FtpRemotePath = ftpRemotePath;
if (!string.IsNullOrWhiteSpace(this._localSavePath) && !Directory.Exists(this._localSavePath))
{
try
{
Directory.CreateDirectory(this._localSavePath);
}
catch { }
}
} public void InitFtp(string ftpServerIp, string ftpUserId, string ftpPassword, string localSavePath)
{
InitFtp(ftpServerIp,"",ftpUserId,ftpPassword,localSavePath);
} /// <summary>
/// 上传
/// </summary>
/// <param name="filename"></param>
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = _ftpUri + fileInf.Name;
FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = null;
try
{
fs = fileInf.OpenRead();
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, , buffLength);
while (contentLen != )
{
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
}
strm.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if(fs!=null)
fs.Close();
}
} public void Upload(byte[] buffer, string filename)
{
string uri = _ftpUri + filename;
FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = buffer.Length;
try
{
Stream strm = reqFTP.GetRequestStream();
strm.Write(buffer, , buffer.Length);
strm.Close();
}
catch (Exception ex)
{
throw ex;
}
} public void Upload(string ftpUri,string ftpUserId,string ftpPassword, string filename)
{
FileStream fs = null;
try
{
FileInfo fileInf = new FileInfo(filename);
string uri = ftpUri + fileInf.Name;
FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserId, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen;
fs = fileInf.OpenRead(); Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, , buffLength);
while (contentLen != )
{
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
}
strm.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
fs.Close();
}
} /// <summary>
/// 下载
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
public string Download(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return null; FtpWebRequest reqFTP;
FileStream outputStream=null;
FileStream fs = null;
string content = "";
try
{
outputStream = new FileStream(_localSavePath + "\\" + fileName, FileMode.Create); reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(_ftpUri + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
var response = (FtpWebResponse)reqFTP.GetResponse();
var ftpStream = response.GetResponseStream();
var cl = response.ContentLength;
var bufferSize = ;
int readCount;
byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, , bufferSize);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpStream.Read(buffer, , bufferSize);
} ftpStream.Close();
outputStream.Close();
response.Close();
//Buffer.Log(string.Format("Ftp文件{1}下载成功!" , DateTime.Now.ToString(), fileName)); fs = new FileStream(_localSavePath + "\\" + fileName, FileMode.Open);
var sr = new StreamReader(fs); content = sr.ReadToEnd(); sr.Close();
fs.Close(); Delete(fileName);
}
catch (Exception ex)
{
if (outputStream != null)
outputStream.Close();
if (fs != null)
fs.Close();
throw ex;
} return content; } public byte[] DownloadByte(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return null; FtpWebRequest reqFTP;
byte[] buff = null;
try
{ reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(_ftpUri + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
var response = (FtpWebResponse)reqFTP.GetResponse();
var ftpStream = response.GetResponseStream(); MemoryStream stmMemory = new MemoryStream();
byte[] buffer = new byte[ * ];
int i;
while ((i = ftpStream.Read(buffer, , buffer.Length)) > )
{
stmMemory.Write(buffer, , i);
}
buff = stmMemory.ToArray();
stmMemory.Close();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
} return buff; } /// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName"></param>
public void Delete(string fileName)
{
try
{
string uri = _ftpUri + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
//Buffer.Log(string.Format("Ftp文件{1}删除成功!", DateTime.Now.ToString(), fileName));
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 删除文件夹(只针对空文件夹)
/// </summary>
/// <param name="folderName"></param>
public void RemoveDirectory(string folderName)
{
try
{
string uri = _ftpUri + folderName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory; string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 删除文件夹以及其下面的所有内容
/// </summary>
/// <param name="ftp">ftp</param>
public void DeleteFtpDirWithAll(FtpClient ftp)
{
string[] fileList = ftp.GetFileList("");//获取所有文件列表(仅文件)
//1.首先删除所有的文件
if (fileList != null && fileList.Length > )
{
foreach (string file in fileList)
{
ftp.Delete(file);
}
} //获取所有文件夹列表(仅文件夹)
string[] emptyDriList = ftp.GetDirectoryList();
foreach (string dir in emptyDriList)
{
//有时候会出现空的子目录,这时候要排除
if (string.IsNullOrWhiteSpace(dir))
{
continue;
} string curDir = "/" + dir;
ftp.FtpRemotePath = ftp.FtpRemotePath + curDir;
//是否有子文件夹存在
if (ftp.GetDirectoryList() != null && ftp.GetDirectoryList().Length > )
{
DeleteFtpDirWithAll(ftp);//如果有就继续递归
}
ftp.FtpRemotePath = ftp.FtpRemotePath.Replace(curDir, "");//回退到上级目录以删除其本身
ftp.RemoveDirectory(dir);//删除当前文件夹
}
} /// <summary>
/// 获取当前目录下明细(包含文件和文件夹)
/// </summary>
/// <returns></returns>
public string[] GetFilesDetailList()
{
//string[] downloadFiles;
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri));
ftp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); //while (reader.Read() > 0)
//{ //}
string line = reader.ReadLine();
//line = reader.ReadLine();
//line = reader.ReadLine(); while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
if (result.Length == )
return null;
result.Remove(result.ToString().LastIndexOf("\n"), );
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{ return null;
}
} /// <summary>
/// 获取当前目录下文件列表(仅文件)
/// </summary>
/// <returns></returns>
public string[] GetFileList(string mask)
{
string[] downloadFiles=null;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); string line = reader.ReadLine();
while (line != null)
{
if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
{ string mask_ = mask.Substring(, mask.IndexOf("*"));
if (line.Substring(, mask_.Length) == mask_)
{
result.Append(line);
result.Append("\n");
}
}
else
{
result.Append(line);
result.Append("\n");
}
line = reader.ReadLine();
}
if (result.Length == )
return new string[]{};
result.Remove(result.ToString().LastIndexOf('\n'), );
reader.Close();
response.Close();
downloadFiles= result.ToString().Split('\n');
}
catch (Exception ex)
{
return new string[] { };
} if (downloadFiles == null)
downloadFiles = new string[] { };
return downloadFiles;
} public string GetSingleFile()
{
var list = GetFileList("*.*"); if (list != null && list.Length > )
return list[];
else
return null;
} /// <summary>
/// 获取当前目录下所有的文件夹列表(仅文件夹)
/// </summary>
/// <returns></returns>
public string[] GetDirectoryList()
{
string[] drectory = GetFilesDetailList();
if (drectory == null)
return null;
string m = string.Empty;
foreach (string str in drectory)
{
int dirPos = str.IndexOf("<DIR>");
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>
/// 判断当前目录下指定的子目录是否存在
/// </summary>
/// <param name="RemoteDirectoryName">指定的目录名</param>
public bool DirectoryExist(string RemoteDirectoryName)
{
string[] dirList = GetDirectoryList();
if (dirList != null)
{
foreach (string str in dirList)
{
if (str.Trim() == RemoteDirectoryName.Trim())
{
return true;
}
}
}
return false;
} /// <summary>
/// 判断当前目录下指定的文件是否存在
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
public bool FileExist(string RemoteFileName)
{
string[] fileList = GetFileList("*.*");
foreach (string str in fileList)
{
if (str.Trim() == RemoteFileName.Trim())
{
return true;
}
}
return false;
} /// <summary>
/// 创建文件夹
/// </summary>
/// <param name="dirName"></param>
public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
// dirName = name of the directory to create.
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream(); ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 获取指定文件大小
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public long GetFileSize(string filename)
{
FtpWebRequest reqFTP;
long fileSize = ;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri + filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength; ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
//throw new Exception("FtpWeb:GetFileSize Error --> " + ex.Message);
}
return fileSize;
} /// <summary>
/// 改名
/// </summary>
/// <param name="currentFilename"></param>
/// <param name="newFilename"></param>
public void ReName(string currentFilename, string newFilename)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri + currentFilename));
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream(); ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 移动文件
/// </summary>
/// <param name="currentFilename"></param>
/// <param name="newFilename"></param>
public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
} }
}

2.调用 DictionaryDelete

   //获取FTP配置信息
string ftpServerIP = System.Configuration.ConfigurationManager.AppSettings["ConfigFTPAddress"].ToString();//FTP地址
string ftpUserName = System.Configuration.ConfigurationManager.AppSettings["ConfigFTPLoginName"].ToString();//FTP登录用户名
string ftpUserPwd = System.Configuration.ConfigurationManager.AppSettings["ConfigFTPLoginPwd"].ToString();//FTP登录密码
string dirName = "10.6.1.140";//这个IP地址只是一个文件夹的名称 /// <summary>
/// 删除文件夹
/// </summary>
private void DictionaryDelete()
{
FtpClient ftp = new FtpClient();
ftp.InitFtp(ftpServerIP, ftpUserName, ftpUserPwd, "");
ftp.FtpRemotePath = dirName;
ftp.DeleteFtpDirWithAll(ftp);
} /// <summary>
/// 创建文件夹
/// </summary>
private void DictionaryCreate()
{
FtpClient ftp = new FtpClient();
ftp.InitFtp(ftpServerIP, ftpUserName, ftpUserPwd, "");
if (!ftp.DirectoryExist(dirName))
{
ftp.MakeDir(dirName);
}
}

3.说明,主要方法是  FtpClient 类中的 DeleteFtpDirWithAll 方法

删除前:

删除后:

C# FTP删除文件以及文件夹的更多相关文章

  1. c#FTP操作类,包含上传,下载,删除,获取FTP文件列表文件夹等Hhelp类

    有些时间没发表文章了,之前用到过,这是我总结出来关于ftp相关操作一些方法,网上也有很多,但是没有那么全面,我的这些仅供参考和借鉴,希望能够帮助到大家,代码和相关引用我都复制粘贴出来了,希望大家喜欢 ...

  2. C#FTP操作类含下载上传删除获取目录文件及子目录列表等等

    ftp登陆格式  : ftp://[帐号]:[密码]@[IP]:[端口] ftp://用户名:密码@FTP服务器IP或域名:FTP命令端口/路径/文件名 直接上代码吧,根据需要选择函数,可根据业务自己 ...

  3. Java创建、重命名、删除文件和文件夹(转)

    Java的文件操作太基础,缺乏很多实用工具,比如对目录的操作,支持就非常的差了.如果你经常用Java操作文件或文件夹,你会觉得反复编写这些代码是令人沮丧的问题,而且要大量用到递归. 下面是的一个解决方 ...

  4. 【数据下载】利用wget命令批量下载ftp文件和文件夹

    这是一个“”数据大发现”的时代,大家都在创造数据,使用数据以及分享数据,首先一步我们就需要从数据库download我们需要的数据. Ftp是一种常见的在线数据库,今天介绍一种可以批量下载文件夹的方法, ...

  5. C# FTP操作类(获取文件和文件夹列表)

    一.如何获取某一目录下的文件和文件夹列表. 由于FtpWebRequest类只提供了WebRequestMethods.Ftp.ListDirectory方式和WebRequestMethods.Ft ...

  6. “打开ftp服务器上的文件夹时发生错误,请检查是否有权限访问该文件夹"

    阿里云虚拟主机上传网站程序 问题场景:网页制作完成后,程序需上传至虚拟主机 注意事项: 1.Windows系统的主机请将全部网页文件直接上传到FTP根目录,即 / . 2. 如果网页文件较多,上传较慢 ...

  7. Java实现FTP文件与文件夹的上传和下载

    Java实现FTP文件与文件夹的上传和下载 FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为"文传协议".用于Internet上的控制 ...

  8. Java 代码完成删除文件、文件夹操作

    import java.io.File;/** * 删除文件和目录 * */public class DeleteFileUtil {    /**     * 删除文件,可以是文件或文件夹     ...

  9. [No000073]C#直接删除指定目录下的所有文件及文件夹(保留目录)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

随机推荐

  1. vue学习(转载)

    vue.js库的基本使用 第一步:下载 官网地址:https://cn.vuejs.org/v2/guide/installation.html 第二步:放到项目的文件目录下 一般新建一个js文件夹, ...

  2. Linux 系统下安装 mysql5.7.25(glibc版)

    前言:经过一天半的折腾,终于把 mysql 5.7.25 版本安装上了 Amazon Linux AMI release 2017.09 系统上,把能参考的博客几乎都看了一遍,终于发现这些细节问题,然 ...

  3. Starting vsftpd for vsftpd: [FAILED]问题的解决

    问题描述 [root@bigdatamaster etc]# rpm -qa| grep vsftpd vsftpd--.el6.x86_64 [root@bigdatamaster etc]# [r ...

  4. OpenGL6-纹理动画

    代码下载 #include "CELLWinApp.hpp"#include <gl/GLU.h>#include <assert.h>#include & ...

  5. centos7 mariadb 设置root密码

    centos7 mariadb 设置root密码   修改root密码1.以root身份在终端登陆,必须2.输入 mysqladmin -u root -p password root后面的 root ...

  6. badboy详解篇

    上一篇学习了jmeter录制的两种方法,badboy是比较好用的一个,它本身就是个测试工具,今天具体来介绍一下: 1.检查点 检查点就是记录被测系统某个值的预期结果 以百度搜索gogomall为例子 ...

  7. 【HTML基础】常用基础标签

    什么是HTML? HTML(HyperText Markup Language,超文本标记语言),所谓超文本就是指页面内可以包含图片.链接.甚至音乐等非文字元素,HTML不是一种编程语言,而是一种标记 ...

  8. Environment.Exit(0) 、Application.Exit() 、this.Close() 、this.Dispose()的区别

    Application.Exit:通知winform消息循环退出.程序会等待所有的前台线程终止后才能真正退出.是一种强行退出方式,就像 Win32 的 PostQuitMessage().它意味着放弃 ...

  9. JSON跨域问题总结

    一.跨域问题的原因: 1 浏览器的检查 2 跨域 3 XMLHttpRequest请求二.跨域问题的解决: 1 禁止浏览器检查:使用dos命令,在启动浏览器的时候,加一个参数:chrome --dis ...

  10. 深入理解JavaScript系列(44):设计模式之桥接模式

    介绍 桥接模式(Bridge)将抽象部分与它的实现部分分离,使它们都可以独立地变化. 正文 桥接模式最常用在事件监控上,先看一段代码: addEvent(element, 'click', getBe ...