转载:http://blog.csdn.net/gdjlc/article/details/11968477

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; }
}

开源.NET FTP组件edtFTPnet 用法

http://www.cnblogs.com/gdjlc/p/3341000.html

【C#】工具类-FTP操作封装类FTPHelper的更多相关文章

  1. java工具类--数据库操作封装类

    java对数据库操作简单处理,如下代码即可,封装了 增删改查及获取连接.关闭连接. 代码如下: package com.test; import java.sql.Connection; import ...

  2. C#一个FTP操作封装类FTPHelper

    参考了网上一些代码,作了一些调整优化. 001 using System; 002 using System.Collections.Generic; 003 using System.Linq; 0 ...

  3. C#常用工具类——Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

  4. [C#] 常用工具类——文件操作类

    /// <para> FilesUpload:工具方法:ASP.NET上传文件的方法</para> /// <para> FileExists:返回文件是否存在&l ...

  5. C#常用工具类——Excel操作类(ZT)

    本文转载于: http://www.cnblogs.com/zfanlong1314/p/3916047.html /// 常用工具类——Excel操作类 /// <para> ----- ...

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

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

  7. java Arrays工具类的操作

    package java08; /* java.util.Arrays是一个与数组相关的工具类,里面提供了大量的静态方法,用来实现数组常见的操作 public static String toStri ...

  8. [C#]工具类—FTP上传下载

    public class FtpHelper { /// <summary> /// ftp方式上传 /// </summary> public static int Uplo ...

  9. Asp.Net 常用工具类---Config操作(7)

    近期工作比较忙,忙到忘记写博客(自己的借口,主要加班下班后不想动). 月初的时候,打算每两天写一篇博文,分享自己的一些心得和开发体验,无奈现在只写到第六篇,然而时间已经是20号,岁月不饶人! 总想写点 ...

随机推荐

  1. 构建高性能web站点--读书大纲

    用户输入你的站点网址,等了半天..还没打开,裤衩一下就给关了.好了,流失了一个用户.为什么会有这样的问题呢.怎么解决自己站点“慢”,体验差的问题呢. 在这段等待的时间里,到底发生了什么?事实上这并不简 ...

  2. 用VS2010打开vs2008

    用VS2010打开vs2008,对应的9.0.0.0版本,而应该该使用版本10.0.0.0 解决方案:修改配置文件.将Microsoft.ReportViewer的版本为9.0.0.0改为10.0.0 ...

  3. smarty缓存函数

    原来在Smarty中在3.0以上版本中不在使用这个clear_all_cache(),而是以$smarty->clearAllCache(); 代替.其中$smarty->clear_ca ...

  4. 实现两个N*N矩阵的乘法,矩阵由一维数组表示

    实现两个N*N矩阵的乘法,矩阵由一维数组表示. 先介绍一下矩阵的加法: void Add(int rows, int cols) { ;i<rows;i++) { ;j<cols;j++) ...

  5. 猎豹使用AI RoboForm填表

    最近,Chrome同步书签好慢,另外因为工作的原因,chrome还是用来做工作的事情,自己的事情准备换到猎豹,但是一个重要的问题是强大的自动填表工具AI RoboForm没有整合到猎豹的地方: 搜索了 ...

  6. 把两个DataTable连接起来,相当于Sql的Inner Join方法

    在C#中把两个DataTable连接起来,相当于Sql的Inner Join方法 作者:浪漫十一狼在下面的例子中实现了3个Join方法,其目的是把两个DataTable连接起来,相当于Sql的Inne ...

  7. Android百度地图开发(三)范围搜索

    // 1.新建项目 将地图API添加进classpath中: 2.在activity_main.xml中添加一个MapView,用来显示地图: <LinearLayout xmlns:andro ...

  8. ps制作哈7海报字体

    模仿也需要较强的功底和分析思路.如下面的教程,作者模仿的是电影海报字.文字构造虽不复杂,不过思路不对的话就容易走弯路.最终效果 1.先来分析文字的构造,大致由两部分组成,一部分是浮雕字,另一部分是质感 ...

  9. SVN的搭建和使用总结

    Subversion是优秀的版本控制工具,其具体的的优点和详细介绍就不多做介绍,主要说一下SVN的服务端搭建.客户端安装.使用及出现的问题的解决办法. 首先来下载和搭建SVN服务器. 现在Subver ...

  10. LeetCode(3) - Longest Substring Without Repeating Characters

    这题的题意大概就是给你一个字符串"abcdecde",找到最长的子字符串长度,里面所有的子母都不重复.本例子中最长的满足条件的子字符串就是"abcde",所以应 ...