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. 3.nginx日志

    1. 自定义日志格式为json log_format json '{"@timestamp":"$time_iso8601",' '"@version ...

  2. hive DML

    1.load files into tables 把文件中的数据加载到表中(表必须先建好) 语法是: load data [local] inpath 'filepath' [overwrite] i ...

  3. SpringCloud---消息驱动的微服务---Spring Cloud Stream

    1.概述 1.1 Spring Cloud Stream:用来   为微服务应用   构建   消息驱动能力的框架: 可基于SpringBoot来创建独立.可用于生产的Spring应用程序: 使用Sp ...

  4. Android deeplink和AppLink原理

    APP开发中经常会有这种需求:在浏览器或者短信中唤起APP,如果安装了就唤起,否则引导下载.对于Android而言,这里主要牵扯的技术就是deeplink,也可以简单看成scheme,Android一 ...

  5. unity 渲染第二步

    先不要用 unity shader 提供给你的转换矩阵,看看屏幕上的图形,你会学到更多. --- <unity 渲染箴言> 假设你 create 了一个 cube,放在默认的位置,默认的 ...

  6. 基于URL权限拦截的实现

    一.实现原理 1.实现原理   本示例采用SpringMVC的拦截器来实现一个基于URL的权限拦截. 2.权限管理流程 二.数据库搭建 1.用户表(sys_user) (1)表结构 (2)表字段说明 ...

  7. Linux修改命令行样式

    Linux修改Shell命令提示符及颜色 Linux修改Shell命令提示符及颜色 1. Linux登录过程中加载配置文件顺序: /etc/profile → /etc/profile.d/*.sh ...

  8. 关于vue的常识问题及解决方法

    一.VSCode开发必备插件 1.Beautify:语法高亮: 2.Bracket Pair Colorizer :对括号对进行着色: 3.ESLint:ESLint插件,高亮提示: 4.HTML C ...

  9. wcf datetime json format

    wcf 内置的json序列化工具,有时需要替换,或者特殊情况的处理,需要修改. 我也遇到了Dto属性类型是datetime,json的反序列化 和 序列号不友好. 这是国外网站的一个方案:Replac ...

  10. Db - DataAccess

    /* Jonney Create 2013-8-12 */ /*using System.Data.OracleClient;*/ /*using System.Data.SQLite;*/ /*us ...