【转载】C#工具类:FTP操作辅助类FTPHelper
FTP是一个8位的客户端-服务器协议,能操作任何类型的文件而不需要进一步处理,就像MIME或Unicode一样。可以通过C#中的FtpWebRequest类、NetworkCredential类、WebRequestMethods类来实现一个FTP操作的相关辅助类FTPHelper。
先来看MSDN关于上述几个类的定义以及解释:
FtpWebRequest类:实现文件传输协议 (FTP) 客户端。若要获取的实例FtpWebRequest,使用Create方法。 此外可以使用WebClient类来上传和下载信息从 FTP 服务器。 使用任一种方法,当您指定使用 FTP 方案的网络资源 (例如, "ftp://contoso.com"
)FtpWebRequest类提供了能够以编程方式与 FTP 服务器进行交互。
NetworkCredential类:为基于密码的身份验证方案(如基本、摘要式、NTLM 和 Kerberos 身份验证)提供凭据。
WebRequestMethods类:WebRequestMethods.Ftp、WebRequestMethods.File 和 WebRequestMethods.Http 类的容器类。 无法继承此类。
封装好的FTPHelper帮助类如下,包含连接FTP服务器、上传文件到FTP服务器、下载FTP服务器文件、删除FTP服务器文件、获取当前目录下明细等几个常用方法。具体实现如下:
public class FTPHelper
{
#region 字段
string ftpURI;
string ftpUserID;
string ftpServerIP;
string ftpPassword;
string ftpRemotePath;
#endregion
/// <summary>
/// 连接FTP服务器
/// </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)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
/// <summary>
/// 上传
/// </summary>
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, , buffLength);
while (contentLen != )
{
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 下载
/// </summary>
public void Download(string filePath, string fileName)
{
try
{
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
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);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 删除文件
/// </summary>
public void Delete(string fileName)
{
try
{
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
reqFTP.KeepAlive = false;
string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 获取当前目录下明细(包含文件和文件夹)
/// </summary>
public string[] GetFilesDetailList()
{
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
line = reader.ReadLine();
line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf("\n"), );
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 获取FTP文件列表(包括文件夹)
/// </summary>
private string[] GetAllList(string url)
{
List<string> list = new List<string>();
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url));
req.Credentials = new NetworkCredential(ftpPassword, ftpPassword);
req.Method = WebRequestMethods.Ftp.ListDirectory;
req.UseBinary = true;
req.UsePassive = true;
try
{
using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
string s;
while ((s = sr.ReadLine()) != null)
{
list.Add(s);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return list.ToArray();
}
/// <summary>
/// 获取当前目录下文件列表(不包括文件夹)
/// </summary>
public string[] GetFileList(string url)
{
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpPassword, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
if (line.IndexOf("<DIR>") == -)
{
result.Append(Regex.Match(line, @"[\S]+ [\S]+", RegexOptions.IgnoreCase).Value.Split(' ')[]);
result.Append("\n");
}
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), );
reader.Close();
response.Close();
}
catch (Exception ex)
{
throw (ex);
}
return result.ToString().Split('\n');
}
/// <summary>
/// 判断当前目录下指定的文件是否存在
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
public bool FileExist(string RemoteFileName)
{
string[] fileList = GetFileList("*.*");
foreach (string str in fileList)
{
if (str.Trim() == RemoteFileName.Trim())
{
return true;
}
}
return false;
}
/// <summary>
/// 创建文件夹
/// </summary>
public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{ }
}
/// <summary>
/// 获取指定文件大小
/// </summary>
public long GetFileSize(string filename)
{
FtpWebRequest reqFTP;
long fileSize = ;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{ }
return fileSize;
}
/// <summary>
/// 更改文件名
/// </summary>
public void ReName(string currentFilename, string newFilename)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{ }
}
/// <summary>
/// 移动文件
/// </summary>
public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
}
/// <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 + "/";
}
}
备注:此文章转载自C#工具类:FTP操作辅助类FTPHelper_IT技术小趣屋。
博主个人技术交流群:960640092,博主微信公众号如下:
【转载】C#工具类:FTP操作辅助类FTPHelper的更多相关文章
- 【C#】工具类-FTP操作封装类FTPHelper
转载:http://blog.csdn.net/gdjlc/article/details/11968477 using System; using System.Collections.Generi ...
- C#常用工具类——Excel操作类(ZT)
本文转载于: http://www.cnblogs.com/zfanlong1314/p/3916047.html /// 常用工具类——Excel操作类 /// <para> ----- ...
- C#常用工具类——Excel操作类
/// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...
- [C#] 常用工具类——文件操作类
/// <para> FilesUpload:工具方法:ASP.NET上传文件的方法</para> /// <para> FileExists:返回文件是否存在&l ...
- java工具类--数据库操作封装类
java对数据库操作简单处理,如下代码即可,封装了 增删改查及获取连接.关闭连接. 代码如下: package com.test; import java.sql.Connection; import ...
- [转载]Process工具类,提供设置timeout功能
FROM:http://segmentfault.com/blog/lidonghao/1190000000372535 在前一篇博文中,简单介绍了如何使用Process类来调用命令行的功能,那样使用 ...
- java Arrays工具类的操作
package java08; /* java.util.Arrays是一个与数组相关的工具类,里面提供了大量的静态方法,用来实现数组常见的操作 public static String toStri ...
- [C#]工具类—FTP上传下载
public class FtpHelper { /// <summary> /// ftp方式上传 /// </summary> public static int Uplo ...
- Asp.Net 常用工具类---Config操作(7)
近期工作比较忙,忙到忘记写博客(自己的借口,主要加班下班后不想动). 月初的时候,打算每两天写一篇博文,分享自己的一些心得和开发体验,无奈现在只写到第六篇,然而时间已经是20号,岁月不饶人! 总想写点 ...
随机推荐
- 关于整数溢出和NaN的问题
当Integer i = Integer.MAX_VALUE;i + 1 < i成立, Double.NaN与任何数(包括自己)比较都为false,与js的NaN一样 如下: //整数溢出 In ...
- PB开发境界 多个DW进行update
多个DW进行update //菜鸟代码dw_1.Update()dw_2.Update()初级代码IF dw_1.Update() = 1 And dw_2.Update() = 1 THEN ...
- centos7使用wordpress布署网站(2)
1.接下来需要配置数据库,为使用wordpress做准备 修改认证方式: vim .../phpMyAdmin/config.inc.php [...] $cfg['Servers'][$i]['au ...
- Kali学习笔记18:OpenVAS使用
上一篇讲了什么是OpenVAS以及如何安装: https://www.cnblogs.com/xuyiqing/p/9690373.html 接下来就是使用: 我先打开一台Metasploitable ...
- Mybatis框架七:三种方式整合Spring
需要的jar包: 新建lib文件夹放入jar包,Build Path-->Add To Build Path之后: 原始Dao开发示例: src下:新建核心配置文件sqlMapConfig.xm ...
- LabVIEW(九):程序结构中的分支结构和顺序结构
一.分支结构 1.创建分支结构:程序框图右键>结构>条件结构 2.Ctrl + I 会显示错误列表,双击错误列表会定位到该错误在程序框图中地方. 3.有的分支可以不连接分支内容. 在不连接 ...
- Spark基础-scala学习(四、函数式编程)
函数式编程 将函数赋值给变量 匿名函数 高阶函数 高级函数的类型推断 scala的常用高阶函数 闭包 sam转换 currying函数 return 将函数赋值给变量 scala中的函数是一等公民,可 ...
- python2程序移植python3的一些注意事项
1 queue: python2: import Queue python3: import queue 2 queue size: python2: cache = Queue.Queue(maxs ...
- ubuntu垃圾文件清理方法
linux和windows系统不同,linux不会产生无用垃圾文件,但是在升级缓存中,linux不会自动删除这些文件,今天就来说说这些垃圾文件清理方法. 1,非常有用的清理命令:sudo apt-ge ...
- tensorflow 1.0 学习:参数初始化(initializer)
CNN中最重要的就是参数了,包括W,b. 我们训练CNN的最终目的就是得到最好的参数,使得目标函数取得最小值.参数的初始化也同样重要,因此微调受到很多人的重视,那么tf提供了哪些初始化参数的方法呢,我 ...