using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Globalization;
using System.Text.RegularExpressions;
namespace System.Net.Ftp
{
///
/// FTP处理操作类
/// 功能:
/// 下载文件
/// 上传文件
/// 上传文件的进度信息
/// 下载文件的进度信息
/// 删除文件
/// 列出文件
/// 列出目录
/// 进入子目录
/// 退出当前目录返回上一层目录
/// 判断远程文件是否存在
/// 判断远程文件是否存在
/// 删除远程文件
/// 建立目录
/// 删除目录
/// 文件(目录)改名
///
///
/// 创建人:南疯
/// 创建时间:2007年4月28日
///
#region 文件信息结构
public struct FileStruct
{
public string Flags;
public string Owner;
public string Group;
public bool IsDirectory;
public DateTime CreateTime;
public string Name;
}
public enum FileListStyle
{
UnixStyle,
WindowsStyle,
Unknown
}
#endregion
public class clsFTP
{
#region 属性信息
///
/// FTP请求对象
///
FtpWebRequest Request = null;
///
/// FTP响应对象
///
FtpWebResponse Response = null;
///
/// FTP服务器地址
///
private Uri _Uri;
///
/// FTP服务器地址
///
public Uri Uri
{
get
{
if (_DirectoryPath == "/")
{
return _Uri;
}
else
{
string strUri = _Uri.ToString();
if (strUri.EndsWith("/"))
{
strUri = strUri.Substring(0, strUri.Length - 1);
}
return new Uri(strUri + this.DirectoryPath);
}
}
set
{
if (value.Scheme != Uri.UriSchemeFtp)
{
throw new Exception("Ftp 地址格式错误!");
}
_Uri = new Uri(value.GetLeftPart(UriPartial.Authority));
_DirectoryPath = value.AbsolutePath;
if (!_DirectoryPath.EndsWith("/"))
{
_DirectoryPath += "/";
}
}
}
///
/// 当前工作目录
///
private string _DirectoryPath;
///
/// 当前工作目录
///
public string DirectoryPath
{
get { return _DirectoryPath; }
set { _DirectoryPath = value; }
}
///
/// FTP登录用户
///
private string _UserName;
///
/// FTP登录用户
///
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
///
/// 错误信息
///
private string _ErrorMsg;
///
/// 错误信息
///
public string ErrorMsg
{
get { return _ErrorMsg; }
set { _ErrorMsg = value; }
}
///
/// FTP登录密码
///
private string _Password;
///
/// FTP登录密码
///
public string Password
{
get { return _Password; }
set { _Password = value; }
}
///
/// 连接FTP服务器的代理服务
///
private WebProxy _Proxy = null;
///
/// 连接FTP服务器的代理服务
///
public WebProxy Proxy
{
get
{
return _Proxy;
}
set
{
_Proxy = value;
}
}
///
/// 是否需要删除临时文件
///
private bool _isDeleteTempFile = false;
///
/// 异步上传所临时生成的文件
///
private string _UploadTempFile = "";
#endregion
#region 事件
public delegate void De_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e);
public delegate void De_DownloadDataCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
public delegate void De_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e);
public delegate void De_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e);
///
/// 异步下载进度发生改变触发的事件
/// public event De_DownloadProgressChanged DownloadProgressChanged;
///
/// 异步下载文件完成之后触发的事件
/// public event De_DownloadDataCompleted DownloadDataCompleted;
///
/// 异步上传进度发生改变触发的事件
/// public event De_UploadProgressChanged UploadProgressChanged;
///
/// 异步上传文件完成之后触发的事件
/// public event De_UploadFileCompleted UploadFileCompleted;
#endregion
#region 构造析构函数
///
/// 构造函数
/// ///
FTP地址
///
登录用户名
///
登录密码
public clsFTP(Uri FtpUri, string strUserName, string strPassword)
{
this._Uri = new Uri(FtpUri.GetLeftPart(UriPartial.Authority));
_DirectoryPath = FtpUri.AbsolutePath;
if (!_DirectoryPath.EndsWith("/"))
{
_DirectoryPath += "/";
}
this._UserName = strUserName;
this._Password = strPassword;
this._Proxy = null;
}
///
/// 构造函数
/// ///
FTP地址
///
登录用户名
///
登录密码
///
连接代理
public clsFTP(Uri FtpUri, string strUserName, string strPassword, WebProxy objProxy)
{
this._Uri = new Uri(FtpUri.GetLeftPart(UriPartial.Authority));
_DirectoryPath = FtpUri.AbsolutePath;
if (!_DirectoryPath.EndsWith("/"))
{
_DirectoryPath += "/";
}
this._UserName = strUserName;
this._Password = strPassword;
this._Proxy = objProxy;
}
///
/// 构造函数
/// public clsFTP()
{
this._UserName = "anonymous"; //匿名用户
this._Password = "@anonymous";
this._Uri = null;
this._Proxy = null;
}
///
/// 析构函数
/// ~clsFTP()
{
if (Response != null)
{
Response.Close();
Response = null;
}
if (Request != null)
{
Request.Abort();
Request = null;
}
}
#endregion
#region 建立连接
///
/// 建立FTP链接,返回响应对象
/// ///
FTP地址
///
操作命令
private FtpWebResponse Open(Uri uri, string FtpMathod)
{
try
{
Request = (FtpWebRequest)WebRequest.Create(uri);
Request.Method = FtpMathod;
Request.UseBinary = true;
Request.Credentials = new NetworkCredential(this.UserName, this.Password);
if (this.Proxy != null)
{
Request.Proxy = this.Proxy;
}
return (FtpWebResponse)Request.GetResponse();
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
///
/// 建立FTP链接,返回请求对象
/// ///
FTP地址
///
操作命令
private FtpWebRequest OpenRequest(Uri uri, string FtpMathod)
{
try
{
Request = (FtpWebRequest)WebRequest.Create(uri);
Request.Method = FtpMathod;
Request.UseBinary = true;
Request.Credentials = new NetworkCredential(this.UserName, this.Password);
if (this.Proxy != null)
{
Request.Proxy = this.Proxy;
}
return Request;
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
#endregion
#region 下载文件
///
/// 从FTP服务器下载文件,使用与远程文件同名的文件名来保存文件
/// ///
远程文件名
///
本地路径
public bool DownloadFile(string RemoteFileName, string LocalPath)
{
return DownloadFile(RemoteFileName, LocalPath, RemoteFileName);
}
///
/// 从FTP服务器下载文件,指定本地路径和本地文件名
/// ///
远程文件名
///
本地路径
///
保存文件的本地路径,后面带有"\"
///
保存本地的文件名
public bool DownloadFile(string RemoteFileName, string LocalPath, string LocalFileName)
{
byte[] bt = null;
try
{
if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(LocalFileName) || !IsValidPathChars(LocalPath))
{
throw new Exception("非法文件名或目录名!");
}
if (!Directory.Exists(LocalPath))
{
throw new Exception("本地文件路径不存在!");
}
string LocalFullPath = Path.Combine(LocalPath, LocalFileName);
if (File.Exists(LocalFullPath))
{
throw new Exception("当前路径下已经存在同名文件!");
}
bt = DownloadFile(RemoteFileName);
if (bt != null)
{
FileStream stream = new FileStream(LocalFullPath, FileMode.Create);
stream.Write(bt, 0, bt.Length);
stream.Flush();
stream.Close();
return true;
}
else
{
return false;
}
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
///
/// 从FTP服务器下载文件,返回文件二进制数据
/// ///
远程文件名
public byte[] DownloadFile(string RemoteFileName)
{
try
{
if (!IsValidFileChars(RemoteFileName))
{
throw new Exception("非法文件名或目录名!");
}
Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DownloadFile);
Stream Reader = Response.GetResponseStream();
MemoryStream mem = new MemoryStream(1024 * 500);
byte[] buffer = new byte[1024];
int bytesRead = 0;
int TotalByteRead = 0;
while (true)
{
bytesRead = Reader.Read(buffer, 0, buffer.Length);
TotalByteRead += bytesRead;
if (bytesRead == 0)
break;
mem.Write(buffer, 0, bytesRead);
}
if (mem.Length > 0)
{
return mem.ToArray();
}
else
{
return null;
}
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
#endregion
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/22392018/viewspace-712366/
,如需转载,请注明出处,否则将追究法律责任。