using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace Utils
{
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 + "/";
} /// <summary>
/// 析构函数
/// </summary>
~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; }
}
}

C# FTPHelper(搬运)的更多相关文章

  1. 关于codeblock中一些常用的快捷键(搬运)

    关于codeblock中一些常用的快捷键(搬运) codeblock作为一个常用的C/C++编译器,是我最常用的一款编译器,但也因为常用,所以有时为了更加快速的操作难免会用到一些快捷键,但是因为我本身 ...

  2. 搬运:Python for Windows——监控Windows某个目录下文件的变化

    https://win32com.goermezer.de/content/view/286/285/ 这个网站真是给力,不多说,代码直接搬运过来,还有我的测试结果,拿走不谢! import os i ...

  3. BizTalk开发系列(二) "Hello World" 程序搬运文件

    我们在<QuickLearn BizTalk系列之"Hello World">里讲到了如何快速的开发第一个BizTalk 应用程序.现在我们来讲一下如何把这个程序改成用 ...

  4. C#操作FTP, FTPHelper和SFTPHelper

    1. FTPHelper using System; using System.Collections.Generic; using System.IO; using System.Net; usin ...

  5. 【C#】工具类-FTP操作封装类FTPHelper

    转载:http://blog.csdn.net/gdjlc/article/details/11968477 using System; using System.Collections.Generi ...

  6. [置顶] 《算法导论》习题解答搬运&&学习笔记 索引目录

    开始学习<算法导论>了,虽然是本大部头,可能很难一下子看完,我还是会慢慢地研究的. 课后的习题和思考有些是很有挑战性的题目,我等蒻菜很难独立解决. 然后发现了Google上有挺全的algo ...

  7. (搬运)《算法导论》习题解答 Chapter 22.1-1(入度和出度)

    (搬运)<算法导论>习题解答 Chapter 22.1-1(入度和出度) 思路:遍历邻接列表即可; 伪代码: for u 属于 Vertex for v属于 Adj[u] outdegre ...

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

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

  9. 货物搬运(move)

    货物搬运(move) 题目描述 天地无情人有情,一方有难八方支援!汶川大地震发生后,灾区最紧缺的是救灾帐篷,全国各地支援的帐篷正紧急向灾区运送.假设围绕纹川县有环行排列的n个救灾帐篷的存储点,每个存储 ...

随机推荐

  1. [Framework Design Guideline]

    [Framework Design Guideline]基础知识 最近在读<Framework design guideline>, 感觉其中Framework的许多设计经验同样适用于业务 ...

  2. CompareValues标签对Model中的属性进行验证

    在Asp.Net MVC中实现CompareValues标签对Model中的属性进行验证   在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现Model两个 ...

  3. Scientific Toolworks Understand for linux安装方法

    1.首先从官网http://www.scitools.com/download/index.php下载Linux版本 2.解压到安装目录下: 32位:gzip -cd Understand-3.1.6 ...

  4. SZU:D89 The Settlers of Catan

    Judge Info Memory Limit: 65536KB Case Time Limit: 3000MS Time Limit: 3000MS Judger: Number Only Judg ...

  5. SZU:B85 Alec's Eggs

    Description Eggs Alec has a lot of eggs. One day, he want to sort them in a ascending sequence by we ...

  6. Python的RotatingFileHandler的Bug

    Python的库非常强大,基本能找到我们所有需要的lib.logging模块是Python中的日志记录库,借鉴了Java中的LOG4J模块的思想,能非常方便的用于记录软件执行日志. 最近有在开发自动化 ...

  7. 10.26最后的模拟DAY2 改造二叉树[中序遍历+严格递增的最长不下降子序列]

    改造二叉树 [题目描述] 小Y在学树论时看到了有关二叉树的介绍:在计算机科学中,二叉树是每个结点最多有两个子结点的有序树.通常子结点被称作“左孩子”和“右孩子”.二叉树被用作二叉搜索树和二叉堆.随后他 ...

  8. JavaScript事件的几个细节

    JavaScript事件的几个细节 一.是捕获还是冒泡 昨天被问到一个问题:事件流有几个阶段?在这几个阶段中,事件一共发生几次? 问题很简单,但对于事件一共发生几次有点乱.总觉得捕获也能触发事件.冒泡 ...

  9. Linux下搭建Nginx+MySQL+PHP

    在CentOS6.3下实践通过. 1.关闭防火墙 [root@CentOS ~]# chkconfig iptables off 2.关闭selinux vi /etc/sysconfig/selin ...

  10. 学习ExpressionTree(做装配脑袋出的练习题)

    1 // 第一题:画出下列表达式的表达式树.一开始,您很可能不知道某些操作其实也是表达式(比如取数组的运算符a[2]),不过没有关系,后面的习题将帮你验证这一点. //-a ParameterExpr ...