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. RabbitMQ---初识

    1.概述 1.1 RabbitMQ   是  实现了   高级消息队列协议(AMQP) 的开源   消息代理软件,也称为  面向消息的中间件: AMQP:Advanced Message Queuin ...

  2. mysql编码不统一形成的错误

    错误提示:[Err]1267 - Illegal mix of collations(utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) ...

  3. Java 继承学习

    Java 继承 继承实现: 在Java中,如果实现继承的,需要使用Java关键字——extends : 被继承的类叫做超类,继承超类的类叫子类.(一个子类亦可以是另一个类的超类) class 子类 e ...

  4. (转)Systemd 入门教程:命令篇

    Systemd 入门教程:命令篇 原文:http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html Systemd 入门 ...

  5. Robot Framework常用关键字介绍

    常用关键字介绍 在学习一门编程语言的时候,大多教材都是从打印“hello world”开始.我们可以像编程语言一样来学习 Robot Framework.虽然通过 RIDE 提供“填表”一样的写测试用 ...

  6. mysql 导入 excel 数据

    客户准备了一些数据存放在   excel 中, 让我们导入到 mysql 中.先上来我自己把数据拷贝到了 txt 文件中, 自己解析 txt 文件,用 JDBC 循环插入到数据库中. 后来发现有更简单 ...

  7. 案例16-validate自定义校验规则校验用户名是否存在

    1 知识点 2 register.jsp代码 注意自定义校验规则的时候,提交必须是同步的方式. <%@ page language="java" contentType=&q ...

  8. GPU体系架构(一):数据的并行处理

    最近在了解GPU架构这方面的内容,由于资料零零散散,所以准备写两篇博客整理一下.GPU的架构复杂无比,这两篇文章也是从宏观的层面去一窥GPU的工作原理罢了 GPU根据厂商的不同,显卡型号的不同,GPU ...

  9. jmeter(3)——录制

    其实自己之前做web功能自动化就接触过录制,不管是火狐浏览器的插件录制,还是QTP的录制,可能刚开始接触你会觉得录制很low,不过,时间长了,有时候录制也是很考验人的,更何况,不管是录制还是脚本,只要 ...

  10. php对图片加水印--将一张图片作为水印加到另一张图片

    代码如下: /**  * 图片加水印(适用于png/jpg/gif格式)  *  * @param $srcImg  原图片  * @param $waterImg 水印图片  * @param $s ...