FTPHelper-封装FTP的相关操作
using System;
using System.IO;
using System.Net;
using System.Text; namespace Whir.Software.DataSyncTools.Library.Helper
{
/// <summary>
/// Ftp辅助类
/// </summary>
public class FtpHelper
{
private const int BufferSize = 2048;
private readonly string _host;
private readonly string _pass;
private readonly string _user;
private FtpWebRequest _ftpRequest;
private FtpWebResponse _ftpResponse;
private Stream _ftpStream; public FtpHelper(string hostIp, string userName, string password)
{
_host = hostIp;
_user = userName;
_pass = password;
} /// <summary>
/// 下载文件
/// </summary>
/// <param name="localFile"></param>
/// <param name="remoteFile"></param>
/// <returns></returns>
public FtpResult Download(string localFile, string remoteFile)
{
FtpResult result;
try
{
_ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + remoteFile);
_ftpRequest.Credentials = new NetworkCredential(_user, _pass);
_ftpRequest.UseBinary = true;
_ftpRequest.UsePassive = true;
_ftpRequest.KeepAlive = true;
_ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
_ftpStream = _ftpResponse.GetResponseStream();
var localFileStream = new FileStream(localFile, FileMode.Create);
var byteBuffer = new byte[BufferSize];
if (_ftpStream != null)
{
int bytesRead = _ftpStream.Read(byteBuffer, 0, BufferSize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = _ftpStream.Read(byteBuffer, 0, BufferSize);
}
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
return result;
}
}
localFileStream.Close();
if (_ftpStream != null) _ftpStream.Close();
_ftpResponse.Close();
_ftpRequest = null;
result = new FtpResult(true, "ok");
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
}
return result;
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="localFile"></param>
/// <param name="remoteFile"></param>
/// <returns></returns>
public FtpResult Upload(string localFile, string remoteFile)
{
FtpResult result;
try
{
_ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + remoteFile);
_ftpRequest.Credentials = new NetworkCredential(_user, _pass);
_ftpRequest.UseBinary = true;
_ftpRequest.UsePassive = true;
_ftpRequest.KeepAlive = true;
_ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
_ftpStream = _ftpRequest.GetRequestStream();
var localFileStream = new FileStream(localFile, FileMode.Create);
var byteBuffer = new byte[BufferSize];
int bytesSent = localFileStream.Read(byteBuffer, 0, BufferSize);
try
{
while (bytesSent != 0)
{
_ftpStream.Write(byteBuffer, 0, bytesSent);
bytesSent = localFileStream.Read(byteBuffer, 0, BufferSize);
}
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
return result;
}
localFileStream.Close();
_ftpStream.Close();
_ftpRequest = null;
result = new FtpResult(true, "ok");
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
}
return result;
} /// <summary>
/// 删除文件
/// </summary>
/// <param name="deleteFile"></param>
public FtpResult Delete(string deleteFile)
{
FtpResult result;
try
{
_ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + deleteFile);
_ftpRequest.Credentials = new NetworkCredential(_user, _pass);
_ftpRequest.UseBinary = true;
_ftpRequest.UsePassive = true;
_ftpRequest.KeepAlive = true;
_ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
_ftpResponse.Close();
_ftpRequest = null;
result = new FtpResult(true, "ok");
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
}
return result;
} /// <summary>
/// 文件重命名
/// </summary>
/// <param name="currentFileNameAndPath"></param>
/// <param name="newFileName"></param>
/// <returns></returns>
public FtpResult Rename(string currentFileNameAndPath, string newFileName)
{
FtpResult result;
try
{
_ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + currentFileNameAndPath);
_ftpRequest.Credentials = new NetworkCredential(_user, _pass);
_ftpRequest.UseBinary = true;
_ftpRequest.UsePassive = true;
_ftpRequest.KeepAlive = true;
_ftpRequest.Method = WebRequestMethods.Ftp.Rename;
_ftpRequest.RenameTo = newFileName;
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
_ftpResponse.Close();
_ftpRequest = null;
result = new FtpResult(true, "ok");
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
}
return result;
} /// <summary>
/// 创建目录
/// </summary>
/// <param name="newDirectory"></param>
/// <returns></returns>
public FtpResult CreateDirectory(string newDirectory)
{
FtpResult result;
try
{
_ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + newDirectory);
_ftpRequest.Credentials = new NetworkCredential(_user, _pass);
_ftpRequest.UseBinary = true;
_ftpRequest.UsePassive = true;
_ftpRequest.KeepAlive = true;
_ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
_ftpResponse.Close();
_ftpRequest = null;
result = new FtpResult(true, "ok");
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
}
return result;
} /// <summary>
/// 取得文件创建时间
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public FtpResult GetFileCreatedDateTime(string fileName)
{
FtpResult result;
try
{
_ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + fileName);
_ftpRequest.Credentials = new NetworkCredential(_user, _pass);
_ftpRequest.UseBinary = true;
_ftpRequest.UsePassive = true;
_ftpRequest.KeepAlive = true;
_ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
_ftpStream = _ftpResponse.GetResponseStream();
if (_ftpStream != null)
{
var ftpReader = new StreamReader(_ftpStream);
string fileInfo;
try
{
fileInfo = ftpReader.ReadToEnd();
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
ftpReader.Close();
if (_ftpStream != null) _ftpStream.Close();
_ftpResponse.Close();
_ftpRequest = null;
return result;
}
ftpReader.Close();
if (_ftpStream != null) _ftpStream.Close();
_ftpResponse.Close();
_ftpRequest = null;
return new FtpResult(true, fileInfo);
}
return new FtpResult(false, "响应流为空");
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
}
return result;
} /// <summary>
/// 取得文件大小
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public FtpResult GetFileSize(string fileName)
{
FtpResult result;
try
{
_ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + fileName);
_ftpRequest.Credentials = new NetworkCredential(_user, _pass);
_ftpRequest.UseBinary = true;
_ftpRequest.UsePassive = true;
_ftpRequest.KeepAlive = true;
_ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
_ftpStream = _ftpResponse.GetResponseStream();
if (_ftpStream != null)
{
var ftpReader = new StreamReader(_ftpStream);
string fileInfo = null;
try
{
while (ftpReader.Peek() != -1)
{
fileInfo = ftpReader.ReadToEnd();
}
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
ftpReader.Close();
if (_ftpStream != null) _ftpStream.Close();
_ftpResponse.Close();
_ftpRequest = null;
return result;
}
ftpReader.Close();
_ftpStream.Close();
_ftpResponse.Close();
_ftpRequest = null;
return new FtpResult(true, fileInfo);
}
result = new FtpResult(false, "响应流为空");
}
catch (Exception ex)
{
result = new FtpResult(false, ex.Message);
}
return result;
} /// <summary>
/// 显示远程目录结构
/// </summary>
/// <param name="directory"></param>
/// <returns></returns>
public string[] DirectoryListSimple(string directory)
{
try
{
_ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + directory);
_ftpRequest.Credentials = new NetworkCredential(_user, _pass);
_ftpRequest.UseBinary = true;
_ftpRequest.UsePassive = true;
_ftpRequest.KeepAlive = true;
_ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
_ftpStream = _ftpResponse.GetResponseStream();
if (_ftpStream != null)
{
var ftpReader = new StreamReader(_ftpStream);
string directoryRaw = null;
try
{
while (ftpReader.Peek() != -1)
{
directoryRaw += ftpReader.ReadLine() + "|";
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
ftpReader.Close();
_ftpStream.Close();
_ftpResponse.Close();
_ftpRequest = null;
/* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
try
{
if (directoryRaw != null)
{
string[] directoryList = directoryRaw.Split("|".ToCharArray());
return directoryList;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return new[] { "" };
} /// <summary>
/// 远程文件列表
/// </summary>
/// <param name="directory"></param>
/// <returns></returns>
public string[] DirectoryListDetailed(string directory)
{
try
{
_ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + directory);
_ftpRequest.Credentials = new NetworkCredential(_user, _pass);
_ftpRequest.UseBinary = true;
_ftpRequest.UsePassive = true;
_ftpRequest.KeepAlive = true;
_ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
_ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
_ftpStream = _ftpResponse.GetResponseStream();
if (_ftpStream != null)
{
var ftpReader = new StreamReader(_ftpStream);
string directoryRaw = null;
try
{
while (ftpReader.Peek() != -1)
{
directoryRaw += ftpReader.ReadLine() + "|";
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
ftpReader.Close();
_ftpStream.Close();
_ftpResponse.Close();
_ftpRequest = null;
try
{
if (directoryRaw != null)
{
string[] directoryList = directoryRaw.Split("|".ToCharArray());
return directoryList;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
/* Return an Empty string Array if an Exception Occurs */
return new[] { "" };
}
} public class FtpResult
{
public FtpResult(bool isCusecess, string message)
{
IsSucess = isCusecess;
Message = message;
} public bool IsSucess { get; set; }
public string Message { get; set; }
}
}
FTPHelper-封装FTP的相关操作的更多相关文章
- cmd 下登陆ftp及相关操作
cmd 下登陆ftp及相关操作 2011-08-09 20:34:28| 分类: 小技巧|字号 订阅 一.举例 假设FTP地址为“ 61.129.83.39”(大家试验的时候不要以这个FTP去试,应 ...
- day17-Python运维开发基础(类的封装 / 对象和类的相关操作、构造方法)
1. 类的封装及相关操作 # ### oop 面向对象程序开发 """ #用几大特征表达一类事物称为一个类,类更像是一张图纸,表达的是一个抽象概念 "" ...
- VC++文件相关操作的函数封装实现
在开发编译工具中,需要用到文件的相关操作,于是就封装了相关的函数实现: //判断文件是否存在 BOOL FileIsExist(CString strFileName) { CFileFind fin ...
- FtpHelper实现ftp服务器文件读写操作(C#)
最近做了一个项目,需要读取ftp服务器上的文件,于是参考了网上提供的一些帮组方法,使用过程中,出现一些小细节问题,于是本人做了一些修改,拿来分享一下 using System; using Syste ...
- Liunx下的有关于tomcat的相关操作 && Liunx 常用指令
先记录以下liunx下的有关于tomcat的相关操作 查看tomcat进程: ps-ef|grep java (回车) 停止tomcat进程: kill -9 PID (进程号如77447) (回车) ...
- Asp.Net Core 2.0 项目实战(4)ADO.NET操作数据库封装、 EF Core操作及实例
Asp.Net Core 2.0 项目实战(1) NCMVC开源下载了 Asp.Net Core 2.0 项目实战(2)NCMVC一个基于Net Core2.0搭建的角色权限管理开发框架 Asp.Ne ...
- python文件相关操作
Python文件相关操作 打开文件 打开文件,采用open方法,会将文件的句柄返回,如下: f = open('test_file.txt','r',encoding='utf-8') 在上面的代码中 ...
- openresty 学习笔记四:连接mysql和进行相关操作
openresty 学习笔记四:连接mysql和进行相关操作 毕竟redis是作为缓存,供程序的快速读写,虽然reidis也可以做持久化保存,但还是需要一个做数据存储的数据库.比如首次查询数据在red ...
- openresty 学习笔记三:连接redis和进行相关操作
openresty 学习笔记三:连接redis和进行相关操作 openresty 因其非阻塞的调用,令服务器拥有高性能高并发,当涉及到数据库操作时,更应该选择有高速读写速度的redis进行数据处理.避 ...
随机推荐
- Installshield 2010 中集成. Net framework4 与 vc++ 2010运行安装包
1.prq的地址,通过以下地址,下载相应的prq文件 VC 2010 redist X86: http://saturn.installshield.com/is/prerequisites/micr ...
- JS实现经典生产者消费者模型
因为node使用单线程的方式实现,所以,在此使用定时器timer取代线程thread来实现生产者消费者模型. 代码例如以下: var sigintCount = 0; var productArray ...
- [Android 新特性] Android 4.3新功能(正式发布前)
腾讯数码讯(编译:徐萧梓丞)虽然谷歌公司目前尚未正式对外发布最新的Android 4.3果冻豆操作系统,但是在上周我们已经看到了关于三星正 在为原生版Galaxy S4进行Android 4.3系统进 ...
- 网络游戏MMORPG服务器架构
转载于:http://justdo2008.iteye.com/blog/1936795 1.网络游戏MMORPG整体服务器框架,包括早期,中期,当前的一些主流架构 .关键词 网络协议 网络IO 消息 ...
- SQLAlchemy如何给列和表添加注释comment?
1.首先需要升级版本到1.2.x,我用的是1.2.14验证的,没有问题 2.看示例: class LoadResource(Base): """施压机资源."& ...
- javascript实现浏览器窗口传递参数
a.html <html> <head> <title>主页面</title> <script language="javascript ...
- java实现ssl单/双向认证通信[推荐]
java实现ssl单/双向认证通信[推荐] 学习了:https://blog.csdn.net/zbuger/article/details/51695582 学习了:https://www.cnbl ...
- JAVA:连接池技术说明以及MVC设计模式理解
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMjgzMDgwNw==/font/5a6L5L2T/fontsize/400/fill/I0JBQk ...
- 阅读《Android 从入门到精通》(24)——切换图片
切换图片(ImageSwitcher) java.lang.Object; android.view.View; android.widget.ViewGroup; android.widget.Fr ...
- Project has no project.properties file! Edit the project properties to set one.
解决办法: 右击项目,选择android tools-->fix project properties.然后重启eclipse即可.