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. [Codeforces Round #351 Div. 2] 673A Bear and Game

    A. Bear and Game time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...

  2. CODEVS【1025】选菜

    1025 选菜  时间限制: 1 s  空间限制: 128000 KB   题目等级 : 黄金 Gold 题目描述 Description 在小松宿舍楼下的不远处,有PK大学最不错的一个食堂——The ...

  3. .NET设计模式系列文章《转》

    原文发布时间为:2008-11-02 -- 来源于本人的百度文章 [由搬家工具导入] http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911 ...

  4. ubuntu php编译安装配置

    安装参考:http://ilanni.blog.51cto.com/526870/1569322/ 加载扩展的一些参数参考:http://java-er.com/blog/nginx-php-fpm/

  5. requireJs杂项

    如果设置了baseUrl,那么baseUrl目录下的模块可以被加载,那么被加载之后的模块Id是什么?文件名吗?     入口函数的写法?是不是要执行,后面加()   中文网中指的优化工具是什么?   ...

  6. autofac 用法总结

    autofac官网: http://autofaccn.readthedocs.io/en/latest/getting-started/index.html autofac作为一个热门ioc框架,还 ...

  7. GCJ——Crazy Rows (2009 Round 2 A)

    题意: 给定一个N*N的矩阵,由0,1组成,只允许交换相邻的两行,把矩阵转化为下三角矩阵(对角线上方全是0),最少需要多少次交换?(保证可以转化为下三角矩阵) Large: N<=40 解析: ...

  8. UVA 11389 The Bus Driver Problem 贪心水题

    题目链接:UVA - 11389 题意描述:有n个司机,n个早班路线和n个晚班路线,给每个司机安排一个早班路线和一个晚班路线,使得每个早班路线和晚班路线只属于一个司机.如果一个司机早班和晚班总的驾驶时 ...

  9. 怎么把一个整数转化为3个十六进制字节 delphi

    如何把一个整数转化为3个十六进制字节 delphi比如把整数149259(都是6位数据整型数) 转换为十六进制为2470B然后再分开为三个字节02 47 0B,求实现代码示例var ID: Integ ...

  10. Android为什么方法数不能超过65535

    言归正传,来聊聊为什么方法数不能超过65535?搬上Dalvik工程师在SF上的回答,因为在Dalvik指令集里,调用方法的invoke-kind指令中,method reference index只 ...