using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO; public class FTPHelper
{
/// <summary>
/// FTP请求对象
/// </summary>
FtpWebRequest request = null;
/// <summary>
/// FTP响应对象
/// </summary>
FtpWebResponse response = null;
/// <summary>
/// FTP服务器地址
/// </summary>
public string ftpURI { get; private set; }
/// <summary>
/// FTP服务器IP
/// </summary>
public string ftpServerIP { get; private set; }
/// <summary>
/// FTP服务器默认目录
/// </summary>
public string ftpRemotePath { get; private set; }
/// <summary>
/// FTP服务器登录用户名
/// </summary>
public string ftpUserID { get; private set; }
/// <summary>
/// FTP服务器登录密码
/// </summary>
public string ftpPassword { get; private set; } /// <summary>
/// 初始化
/// </summary>
/// <param name="FtpServerIP">FTP连接地址</param>
/// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
/// <param name="FtpUserID">用户名</param>
/// <param name="FtpPassword">密码</param>
public FTPHelper(string ftpServerIP, string ftpRemotePath, string ftpUserID, string ftpPassword)
{
this.ftpServerIP = ftpServerIP;
this.ftpRemotePath = ftpRemotePath;
this.ftpUserID = ftpUserID;
this.ftpPassword = ftpPassword;
this.ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
~FTPHelper()
{
if (response != null)
{
response.Close();
response = null;
}
if (request != null)
{
request.Abort();
request = null;
}
}
/// <summary>
/// 建立FTP链接,返回响应对象
/// </summary>
/// <param name="uri">FTP地址</param>
/// <param name="ftpMethod">操作命令</param>
/// <returns></returns>
private FtpWebResponse Open(Uri uri, string ftpMethod)
{
request = (FtpWebRequest)FtpWebRequest.Create(uri);
request.Method = ftpMethod;
request.UseBinary = true;
request.KeepAlive = false;
request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword);
return (FtpWebResponse)request.GetResponse();
} /// <summary>
/// 建立FTP链接,返回请求对象
/// </summary>
/// <param name="uri">FTP地址</param>
/// <param name="ftpMethod">操作命令</param>
private FtpWebRequest OpenRequest(Uri uri, string ftpMethod)
{
request = (FtpWebRequest)WebRequest.Create(uri);
request.Method = ftpMethod;
request.UseBinary = true;
request.KeepAlive = false;
request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword);
return request;
}
/// <summary>
/// 创建目录
/// </summary>
/// <param name="remoteDirectoryName">目录名</param>
public void CreateDirectory(string remoteDirectoryName)
{
response = Open(new Uri(ftpURI + remoteDirectoryName), WebRequestMethods.Ftp.MakeDirectory);
}
/// <summary>
/// 更改目录或文件名
/// </summary>
/// <param name="currentName">当前名称</param>
/// <param name="newName">修改后新名称</param>
public void ReName(string currentName, string newName)
{
request = OpenRequest(new Uri(ftpURI + currentName), WebRequestMethods.Ftp.Rename);
request.RenameTo = newName;
response = (FtpWebResponse)request.GetResponse();
}
/// <summary>
/// 切换当前目录
/// </summary>
/// <param name="IsRoot">true:绝对路径 false:相对路径</param>
public void GotoDirectory(string DirectoryName, bool IsRoot)
{
if (IsRoot)
ftpRemotePath = DirectoryName;
else
ftpRemotePath += "/" + DirectoryName; ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
/// <summary>
/// 删除目录(包括下面所有子目录和子文件)
/// </summary>
/// <param name="remoteDirectoryName">要删除的带路径目录名:如web/test</param>
/*
* 例:删除test目录
FTPHelper helper = new FTPHelper("x.x.x.x", "web", "user", "password");
helper.RemoveDirectory("web/test");
*/
public void RemoveDirectory(string remoteDirectoryName)
{
GotoDirectory(remoteDirectoryName, true);
var listAll = ListFilesAndDirectories();
foreach (var m in listAll)
{
if (m.IsDirectory)
RemoveDirectory(m.Path);
else
DeleteFile(m.Name);
}
GotoDirectory(remoteDirectoryName, true);
response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.RemoveDirectory);
}
/// <summary>
/// 文件上传
/// </summary>
/// <param name="localFilePath">本地文件路径</param>
public void Upload(string localFilePath)
{
FileInfo fileInf = new FileInfo(localFilePath);
request = OpenRequest(new Uri(ftpURI + fileInf.Name), WebRequestMethods.Ftp.UploadFile);
request.ContentLength = fileInf.Length;
int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen;
using (var fs = fileInf.OpenRead())
{
using (var strm = request.GetRequestStream())
{
contentLen = fs.Read(buff, , buffLength);
while (contentLen != )
{
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
}
}
}
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="remoteFileName">要删除的文件名</param>
public void DeleteFile(string remoteFileName)
{
response = Open(new Uri(ftpURI + remoteFileName), WebRequestMethods.Ftp.DeleteFile);
} /// <summary>
/// 获取当前目录的文件和一级子目录信息
/// </summary>
/// <returns></returns>
public List<FileStruct> ListFilesAndDirectories()
{
var fileList = new List<FileStruct>();
response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.ListDirectoryDetails);
using (var stream = response.GetResponseStream())
{
using (var sr = new StreamReader(stream))
{
string line = null;
while ((line = sr.ReadLine()) != null)
{
//line的格式如下:
//08-18-13 11:05PM <DIR> aspnet_client
//09-22-13 11:39PM 2946 Default.aspx
DateTime dtDate = DateTime.ParseExact(line.Substring(, ), "MM-dd-yy", null);
DateTime dtDateTime = DateTime.Parse(dtDate.ToString("yyyy-MM-dd") + line.Substring(, ));
string[] arrs = line.Split(' ');
var model = new FileStruct()
{
IsDirectory = line.IndexOf("<DIR>") > ? true : false,
CreateTime = dtDateTime,
Name = arrs[arrs.Length - ],
Path = ftpRemotePath + "/" + arrs[arrs.Length - ]
};
fileList.Add(model);
}
}
}
return fileList;
}
/// <summary>
/// 列出当前目录的所有文件
/// </summary>
public List<FileStruct> ListFiles()
{
var listAll = ListFilesAndDirectories();
var listFile = listAll.Where(m => m.IsDirectory == false).ToList();
return listFile;
}
/// <summary>
/// 列出当前目录的所有一级子目录
/// </summary>
public List<FileStruct> ListDirectories()
{
var listAll = ListFilesAndDirectories();
var listFile = listAll.Where(m => m.IsDirectory == true).ToList();
return listFile;
}
/// <summary>
/// 判断当前目录下指定的子目录或文件是否存在
/// </summary>
/// <param name="remoteName">指定的目录或文件名</param>
public bool IsExist(string remoteName)
{
var list = ListFilesAndDirectories();
if (list.Count(m => m.Name == remoteName) > )
return true;
return false;
}
/// <summary>
/// 判断当前目录下指定的一级子目录是否存在
/// </summary>
/// <param name="RemoteDirectoryName">指定的目录名</param>
public bool IsDirectoryExist(string remoteDirectoryName)
{
var listDir = ListDirectories();
if (listDir.Count(m => m.Name == remoteDirectoryName) > )
return true;
return false;
}
/// <summary>
/// 判断当前目录下指定的子文件是否存在
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
public bool IsFileExist(string remoteFileName)
{
var listFile = ListFiles();
if (listFile.Count(m => m.Name == remoteFileName) > )
return true;
return false;
} /// <summary>
/// 下载
/// </summary>
/// <param name="saveFilePath">下载后的保存路径</param>
/// <param name="downloadFileName">要下载的文件名</param>
public void Download(string saveFilePath, string downloadFileName)
{
using (FileStream outputStream = new FileStream(saveFilePath + "\\" + downloadFileName, FileMode.Create))
{
response = Open(new Uri(ftpURI + downloadFileName), WebRequestMethods.Ftp.DownloadFile);
using (Stream ftpStream = response.GetResponseStream())
{
long cl = response.ContentLength;
int bufferSize = ;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, , bufferSize);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpStream.Read(buffer, , bufferSize);
}
}
}
} } public class FileStruct
{
/// <summary>
/// 是否为目录
/// </summary>
public bool IsDirectory { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
/// <summary>
/// 文件或目录名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 路径
/// </summary>
public string Path { get; set; }
}

FTPHelper类的更多相关文章

  1. FtpHelper类匿名获取FTP文件

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net ...

  2. C# FTPHelper帮助类

    网上的FTPHelper类感觉用起来不方便,而且代码的质量也不高,因此自己重新写了一个FTPHelper.此文之前是发布在我的CSDN博客中的,现在转过来. 主要就是借鉴了DbHelper的Creat ...

  3. Java类的继承与多态特性-入门笔记

    相信对于继承和多态的概念性我就不在怎么解释啦!不管你是.Net还是Java面向对象编程都是比不缺少一堂课~~Net如此Java亦也有同样的思想成分包含其中. 继承,多态,封装是Java面向对象的3大特 ...

  4. 在附件管理模块中增加对FTP 上传和预览的支持

    在之前介绍的附件管理模块里面<Winform开发框架之通用附件管理模块>以及<Winform开发框架之附件管理应用>,介绍了附件的管理功能,通过对数据库记录的处理和文件的管理, ...

  5. Python3实战系列之四(获取印度售后数据项目)

    问题:续接上一篇.说干咱就干呀,勤勤恳恳写程序呀! 目标:此篇开始进入正题了.为实现我们整个项目功能而开始实现各个子模块功能.首先实现第一篇列出的分步功能模块的第一步: 1.python访问ftp,下 ...

  6. 通过ftp同步服务器文件:遍历文件夹所有文件(含子文件夹、进度条);简单http同步服务器文件实例

    该代码主要实现,指定ftp服务地址,遍历下载该地址下所有文件(含子文件夹下文件),并提供进度条显示:另外附带有通过http地址方式获取服务器文件的简单实例 废话不多说,直接上代码: 1.FTPHelp ...

  7. C# - VS2019WinFrm桌面应用程序FtpClient实现

    前言 本篇主要记录:VS2019 WinFrm桌面应用程序实现简单的FtpClient,包含Ftp文件查看.上传和下载等功能. 准备工作 搭建WinFrm前台界面 添加必要的控件,这里主要应用到Gro ...

  8. [FTP] FTPHelper-FTP帮助类,常用操作方法 (转载)

    点击下载 FTPHelper.zip 这个类是FTP服务器的一些操作1.连接FTP服务器 2.上传3.下载4.删除文件5.获取当前目录下明细(包含文件和文件夹)  6.获取FTP文件列表(包括文件夹) ...

  9. 【转载】C#工具类:FTP操作辅助类FTPHelper

    FTP是一个8位的客户端-服务器协议,能操作任何类型的文件而不需要进一步处理,就像MIME或Unicode一样.可以通过C#中的FtpWebRequest类.NetworkCredential类.We ...

随机推荐

  1. MEF 注入[转载]

    领域服务的时候,用到MEF的注入有参构造函数的方法,your master was attracted,打算稍微深挖一下,这篇来对此知识点做个总结. 一.知识点回顾 MEF作为IOC的方式之一,它的主 ...

  2. [LeetCode] Jump Game II 贪心

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  3. python 集合比较(交集、并集,差集)

    python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和 ...

  4. hdu 4956(思路题)

    Poor Hanamichi Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)To ...

  5. LeetCode OJ-- Add Binary

    https://oj.leetcode.com/problems/add-binary/ 对两个二进制字符串求和. 对于字符串 ans_str,求它的翻转. reverse(ans_str.begin ...

  6. failed to obtain a cell from its dataSource 问题处理

    最近在处理bugly问题的时候,总会看到回话列表有奔溃,但是由于没有啥具体的细节原因也无从下手. 只知道ConversationListViewController这个类的奔溃,报的问题是这个,也只有 ...

  7. my.ini配置详解

    Mysql my.ini 配置文件详解 #BEGIN CONFIG INFO #DESCR: 4GB RAM, 只使用InnoDB, ACID, 少量的连接, 队列负载大 #TYPE: SYSTEM ...

  8. 根据CPU核数合理设置线程池大小

    一般来说池中总线程数是核心池线程数量两倍,只要确保当核心池有线程停止时,核心池外能有线程进入核心池即可. 我们所需要关心的主要是核心池线程的数量该如何设置. 自定义线程池代码 package com. ...

  9. 分享Kali Linux 2017年第17周镜像文件

     分享Kali Linux 2017年第17周镜像文件  Kali Linux官方于4月23日发布2017年的第17周镜像.这次维持了11个镜像文件的规模.默认的Gnome桌面的4个镜像,E17.KD ...

  10. 寒假week1---二分查找(二分枚举)

    寒假week1---二分查找(二分枚举)1.适用条件:要查找(枚举)的集合有序 && 查找(枚举)的“条件”具有单调性2.什么是“条件”:example: 1.给定一个有序数组,从中查 ...