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. numpy多维矩阵,取出第一行或者第一列,方法和df一样

    # 定义一个多维矩阵 arr = np.array([[1,2,3], [4,5,6], [7,8,9]]) # 取出第一行 arr[0,:] # 取出第一列 arr[:,0]

  2. fastclick源码分析

    https://www.cnblogs.com/diver-blogs/p/5657323.html  地址 fastclick.js源码解读分析 阅读优秀的js插件和库源码,可以加深我们对web开发 ...

  3. ViewData与ViewBag的区别

    本文导读:在asp.net mvc程序设计中,传递数据常常会用到viewdata.viewbag.ViewData是一个字典集合,通过key值读取对应的value:ViewBag是动态类型,作用和Vi ...

  4. Robot Framework自动化测试三(selenium API)

    Robot  Framework  Selenium  API 说明: 此文档只是将最常用的UI 操作列出.更多方法请查找selenium2Library 关键字库. 一.浏览器驱动 通过不同的浏览器 ...

  5. Django开发步骤

    Django开发步骤 Django框架每次开发的初始化的套路都基本一样,这里记录一下. 安装Django 首先安装Python软件,上python官网下载对应的安装包.接下来就是安装Django: p ...

  6. 持续集成:TeamCity 的安装和使用

    TeamCity 本文初衷 让大家了解持续集成(CI),以及入门了解 JetBrains 家的 TeamCity 的一些简单实用. TeamCity 的一些复杂使用我暂时也不会,一样也是要看文档的,所 ...

  7. 解决WORD2013输入时光标老跳的问题

    Word2013有一个非常影响使用的bug.就是在编辑文档时,光标会乱跑,影响输入.微软给出了一个kb2863845 160多MB的补丁包,安装完成后就可以解决这个问题.  补丁下载链接: 链接:ht ...

  8. php对图片加水印--将文字作为水印加到图片

    方法代码: /**  * 图片加水印(适用于png/jpg/gif格式)  *  * @author flynetcn  *  * @param $srcImg  原图片  * @param $wat ...

  9. HTML5坦克大战(韩顺平版本)

    HTML5坦克大战(韩顺平版本) 2017-3-22 22:46:22 by SemiconductorKING 去年暑假学习了一下HTML5实现简单的坦克大战,觉得对JavaScript初学者来说, ...

  10. nodejs图片裁剪、水印(使用images)

    /** * Created by chaozhou on 2015/9/21. */ var images = require("images"); /** * 缩放图像 * @p ...