C# FTPHelper(搬运)
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(搬运)的更多相关文章
- 关于codeblock中一些常用的快捷键(搬运)
关于codeblock中一些常用的快捷键(搬运) codeblock作为一个常用的C/C++编译器,是我最常用的一款编译器,但也因为常用,所以有时为了更加快速的操作难免会用到一些快捷键,但是因为我本身 ...
- 搬运:Python for Windows——监控Windows某个目录下文件的变化
https://win32com.goermezer.de/content/view/286/285/ 这个网站真是给力,不多说,代码直接搬运过来,还有我的测试结果,拿走不谢! import os i ...
- BizTalk开发系列(二) "Hello World" 程序搬运文件
我们在<QuickLearn BizTalk系列之"Hello World">里讲到了如何快速的开发第一个BizTalk 应用程序.现在我们来讲一下如何把这个程序改成用 ...
- C#操作FTP, FTPHelper和SFTPHelper
1. FTPHelper using System; using System.Collections.Generic; using System.IO; using System.Net; usin ...
- 【C#】工具类-FTP操作封装类FTPHelper
转载:http://blog.csdn.net/gdjlc/article/details/11968477 using System; using System.Collections.Generi ...
- [置顶] 《算法导论》习题解答搬运&&学习笔记 索引目录
开始学习<算法导论>了,虽然是本大部头,可能很难一下子看完,我还是会慢慢地研究的. 课后的习题和思考有些是很有挑战性的题目,我等蒻菜很难独立解决. 然后发现了Google上有挺全的algo ...
- (搬运)《算法导论》习题解答 Chapter 22.1-1(入度和出度)
(搬运)<算法导论>习题解答 Chapter 22.1-1(入度和出度) 思路:遍历邻接列表即可; 伪代码: for u 属于 Vertex for v属于 Adj[u] outdegre ...
- [FTP] FTPHelper-FTP帮助类,常用操作方法 (转载)
点击下载 FTPHelper.zip 这个类是FTP服务器的一些操作1.连接FTP服务器 2.上传3.下载4.删除文件5.获取当前目录下明细(包含文件和文件夹) 6.获取FTP文件列表(包括文件夹) ...
- 货物搬运(move)
货物搬运(move) 题目描述 天地无情人有情,一方有难八方支援!汶川大地震发生后,灾区最紧缺的是救灾帐篷,全国各地支援的帐篷正紧急向灾区运送.假设围绕纹川县有环行排列的n个救灾帐篷的存储点,每个存储 ...
随机推荐
- 题目要求:建立一个类Str,将一个正整数转换成相应的字符串,例如整数3456转换为字符串"3456".
题目要求:建立一个类Str,将一个正整数转换成相应的字符串,例如整数3456转换为字符串"3456". 关键:怎么将一个数字转换为字符? [cpp] view plaincopy ...
- [转]ANDROID 探究oom内幕
从早期G1的192MB RAM开始,到现在动辄1G -2G RAM的设备,为单个App分配的内存从16MB到48MB甚至更多,但OOM从不曾离我们远去.这是因为大部分App中图片内容占据了50%甚至7 ...
- Unit Of Work-工作单元
Unit Of Work-工作单元 阅读目录: 概念中的理解 代码中的实现 后记 掀起了你的盖头来,让我看你的眼睛,你的眼睛明又亮呀,好像那水波一模样:掀起了你的盖头来,让我看你的脸儿,看看你的脸儿红 ...
- BT是如何下载的
BT协议简介 一.BT下载是怎么来的? 在互联网上下载文件的方式大概有这么几种:FTP.HTTP.BT.eMule(电驴)等, 浏览器会直接支持FTP和HTTP下载,BT和eMule下载一般需要专用的 ...
- AIX errpt命令说明
查看系统的错误记录 在系统运行时,一些系统错误会记录在errlog 中,其中有些错误还会在终端上显示.检查错误日志可用以下命令: # errpt IDENTIFIER TIMESTAM P T ...
- UITableView的style详解
在默认的UITableViewCell中,主要有三个系统控件,分别是两个Lable和一个imageView,两个Label,imageView(始终在最左边)的布局位置可以通过下面4个设置: UITa ...
- C语言中数据类型的长度
面试中C里面int长度经常会被问到,下面总结一下作为资料: 首先看看一般规定: 标准c规定,int长度等于机器字长,short的表示范围不能大于int的表示范围,long的表示范围不能小于int的表示 ...
- DSP TMS320C6000基础学习(4)—— cmd文件分析
DSP中的CMD文件是链接命令文件(Linker Command File),以.cmd为后缀. 在分析cmd文件之前,必需先了解 (1)DSP具体芯片的内存映射(Memory Map) (2)知道点 ...
- Emacs助力PowerShell
Emacs助力PowerShell 阅读目录 1 下载安装Emacs windows版本 2 下载el文件和配置Emacs加载PowerShell 3 体验用Emacs来执行和编辑PowerShell ...
- Jquery文本框值改变事件(支持火狐、ie)
Jquery值改变事件支持火狐和ie浏览器,并且测试通过,绑定后台代码可以做成autocomplete控件. 具体代码列举如下: $(document).ready(function () { $(& ...