using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Configuration;
namespace MvcApplication1
{
public class FTPHelper
{
#region 成员变量
/// <summary>
/// FTP服务器地址
/// </summary>
private static readonly string ftpServerIP = ConfigurationManager.AppSettings["FtpServerIP"];
/// <summary>
/// FTP服务器用户名
/// </summary>
private static readonly string ftpUserID = ConfigurationManager.AppSettings["FtpUserName"];
/// <summary>
/// FTP服务器用户名的密码
/// </summary>
private static readonly string ftpPassword = ConfigurationManager.AppSettings["FtpPassword"];
private static string ftpBaseUrl = @"ftp://" + ftpServerIP + "/";
#endregion
#region 构造方法
//public static FTPOperation()
//{
//}
==============================================================
构造函数名:FTPOperation
/ <summary>
/ 默认构造函数
/ </summary>
/ <remarks>
/ ========================================================================
/ 更新履历
/ 序号 修改日期 责任人 更新内容
/ 001 2010-11-05 武健 新建
/ ========================================================================
/ </remarks>
//public static FTPOperation( string filePath )
//{
//}
#endregion
#region 公共方法
/// 方法功能:获取文件(夹)列表
/// <summary>
/// 获取指定文件夹下面的文件列表(包括文件夹)
/// FTP的根目录下面的虚拟目录无法获取,
/// 所以建议在给FTP网站添加虚拟目录的时候在网站根目录下面添加一个和虚拟目录同名的空文件夹
/// </summary>
/// <param name="path">相对路劲(例如:fold1/fold2/fold3)</param>
/// <returns></returns>
public static List<string> GetDetailList(string path)
{
var _returnList = new List<string>();
FtpWebRequest ftp = CreateFtpRequest(path, WebRequestMethods.Ftp.ListDirectoryDetails);
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
_returnList.Add(line);
line = reader.ReadLine();
}
return _returnList;
}
/// 方法功能:获取文件列表
/// <summary>
/// 获取指定文件夹下面的文件列表(不包括文件夹)
/// </summary>
/// <param name="path">相对路劲(例如:fold1/fold2/fold3)</param>
/// <returns></returns>
public static List<string> GetFileList(string path)
{
var _returnList = new List<string>();
FtpWebRequest ftp = CreateFtpRequest(path, WebRequestMethods.Ftp.ListDirectory);
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
_returnList.Add(line);
line = reader.ReadLine();
}
return _returnList;
}
/// 方法功能:获取文件夹列表
/// <summary>
/// 获取指定目录下面的文件夹列表
/// </summary>
/// <param name="path">相对路劲(例如:fold1/fold2/fold3)</param>
/// <returns></returns>
public static List<string> GetDirectorys(string path)
{
var _detailList = GetDetailList(path).Where(p => p.Contains("<DIR>"));
var _returnList = new List<string>();
foreach (var item in _detailList)
{
_returnList.Add(item.Substring(39));
}
return _returnList;
}
/// 方法功能:判断路劲是否存在(文件夹路劲)
/// <summary>
/// 判断该路劲是否存在
/// </summary>
/// <param name="path">相对路劲(例如:fold1/fold2/fold3)</param>
/// <returns></returns>
public static bool CheckPathExsist(string path)
{
if (string.IsNullOrEmpty(path)) return true;
string[] pathArr = path.Replace('//', '/').Trim('/').Split('/');
string basePath = "";
foreach (var item in pathArr)
{
if (!GetDirectorys(basePath).Contains(item)) return false;
basePath += item + "/";
}
return true;
}
/// 方法功能:判断文件是否存在
/// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="fullPath">相对路劲(例如:fold1/fold2/fold3/index.flv)</param>
/// <returns></returns>
public static bool CheckFileExsist(string fullPath)
{
if (string.IsNullOrEmpty(fullPath)) return false;
string path = "";
if (fullPath.Contains('/') || fullPath.Contains('//'))
{
path = Path.GetDirectoryName(fullPath).Replace('//', '/').Trim('/');
if (!CheckPathExsist(path))
{
return false;
}
}
return GetFileList(path).Contains(path == "" ? fullPath : Path.GetFileName(fullPath));
}
/// 方法功能:创建文件夹
/// <summary>
/// 创建目录(可以任意创建层次目录)
/// </summary>
/// <param name="path">相对路劲(例如:fold1/fold2/fold3)</param>
public static void MakeDirectory(string path)
{
if (string.IsNullOrEmpty(path)) return;
string[] pathArr = path.Replace('//', '/').Trim('/').Split('/');
string basePath = "";
bool pathExsist = true;
foreach (var item in pathArr)
{
if (pathExsist)
{
if (GetDirectorys(basePath).Contains(item))
{
basePath += item + "/";
continue;
}
}
basePath += item + "/";
pathExsist = false;
FtpWebRequest ftp = CreateFtpRequest(basePath, WebRequestMethods.Ftp.MakeDirectory);
WebResponse response = ftp.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
}
/// 方法功能:上传文件
/// <summary>
/// 上传文件
/// </summary>
/// <param name="localPath">本地文件绝对路劲</param>
/// <param name="fullPath">FTP文件路劲</param>
/// <param name="copy">True:复制文件 False:剪切文件</param>
public static bool Upload(string localPath, string fullPath, bool copy)
{
try
{
var _localFileStream = File.Open(localPath, FileMode.Open);
MakeDirectory(Path.GetDirectoryName(fullPath));
FtpWebRequest ftp = CreateFtpRequest(fullPath, WebRequestMethods.Ftp.UploadFile);
// 设定在请求完成之后是否关闭到 FTP 服务器的控制连接
ftp.KeepAlive = false;
// 设定FTP服务器接收文件的大小
ftp.ContentLength = _localFileStream.Length;
// 设定缓存大小
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// 检索用于向 FTP 服务器上载数据的流
Stream _ftpStream = ftp.GetRequestStream();
// 每次按缓存大小读取文件流
contentLen = _localFileStream.Read(buff, 0, buffLength);
while (contentLen != 0)
{
// 将上传文件流写到FTP服务器上载数据流
_ftpStream.Write(buff, 0, contentLen);
contentLen = _localFileStream.Read(buff, 0, buffLength);
}
// 关闭数据流
_ftpStream.Close();
_localFileStream.Close();
if (!copy)
{
File.Delete(localPath);
}
return true;
}
catch
{
return false;
}
}
/// 方法功能:文件下载
/// <summary>
/// 文件下载(暂时有些小问题)
/// 利用保存到本地的临时文件中在进行删除可能比较好(以后再实现)
/// </summary>
/// <param name="fullPath">FTP文件路劲</param>
/// <returns></returns>
public static List<byte> Download(string fullPath)
{
var _returnList = new List<byte>();
FtpWebRequest ftp = CreateFtpRequest(fullPath, WebRequestMethods.Ftp.DownloadFile);
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
// 设定缓存大小
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
Stream _ftpStream = response.GetResponseStream();
while ((contentLen = _ftpStream.Read(buff, 0, buffLength)) != 0)
{
_returnList.AddRange(buff.ToList());
}
// 关闭数据流
_ftpStream.Close();
response.Close();
return _returnList;
}
/// 方法功能:获取文件大小(仅文件)
/// <summary>
/// 获取文件大小
/// 在调用次方法前最好确认这个文件夹是否存在
/// </summary>
/// <param name="fullPath">相对路劲(例如:fold1/fold2/fold3/index.flv)</param>
/// <returns></returns>
public static long GetFileSize(string fullPath)
{
long fileSize = 0;
FtpWebRequest ftp = CreateFtpRequest(fullPath, WebRequestMethods.Ftp.GetFileSize);
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
ftpStream.Close();
response.Close();
return fileSize;
}
/// 方法功能:获取文件时间戳
/// <summary>
/// 获取文件时间戳
/// 在调用次方法前最好确认这个文件夹是否存在
/// </summary>
/// <param name="fullPath">相对路劲(例如:fold1/fold2/fold3/index.flv)</param>
/// <returns></returns>
public static void GetDateTimeStamp(string fullPath)
{
// 暂时未实现
}
/// 方法功能:修改文件夹名称(文件夹或者文件都可以)
/// <summary>
/// 修改文件夹名称
/// </summary>
/// <param name="path">"fold1/fold2"或者"fold1/index.flv"</param>
/// <param name="newPathName"></param>
public static void ChangeFoldName(string path, string newPathName)
{
FtpWebRequest ftp = CreateFtpRequest(path, WebRequestMethods.Ftp.Rename);
ftp.RenameTo = newPathName;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
/// 方法功能:删除文件(仅文件)
/// <summary>
/// 删除文件
/// </summary>
/// <param name="fullPath">例如:"fold1/fold2/index.flv"</param>
public static void Delete(string fullPath)
{
FtpWebRequest ftp = CreateFtpRequest(fullPath, WebRequestMethods.Ftp.DeleteFile);
ftp.KeepAlive = false;
string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
#endregion
#region Private Method
private static FtpWebRequest CreateFtpRequest(string path, string method)
{
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpBaseUrl + path ?? string.Empty));
ftp.Method = method;
ftp.UseBinary = true;
return ftp;
}
#endregion
}
}