using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
namespace Kostech.Net
{
/// <summary>
/// FTP 的摘要说明。
/// </summary>
public class FTP
{
private string strRemoteHost;
private int strRemotePort;
private string strRemotePath;
private string strRemoteUser;
private string strRemotePass;
private Boolean bConnected;
#region 内部变量
/// <summary>
/// 服务器返回的应答信息(包含应答码)
/// </summary>
private string strMsg;
/// <summary>
/// 服务器返回的应答信息(包含应答码)
/// </summary>
private string strReply;
/// <summary>
/// 服务器返回的应答码
/// </summary>
private int iReplyCode;
/// <summary>
/// 进行控制连接的socket
/// </summary>
private Socket socketControl;
/// <summary>
/// 传输模式
/// </summary>
private TransferType trType;
/// <summary>
/// 传输模式:二进制类型、ASCII类型
/// </summary>
public enum TransferType
{
/// <summary>
/// Binary
/// </summary>
Binary,
/// <summary>
/// ASCII
/// </summary>
ASCII
};
/// <summary>
/// 接收和发送数据的缓冲区
/// </summary>
private static int BLOCK_SIZE = 512;
Byte[] buffer = new Byte[ BLOCK_SIZE];
/// <summary>
/// 编码方式
/// </summary>
Encoding ASCII = Encoding.Default;
#endregion
#region 内部函数
#region 构造函数
/// <summary>
/// 缺省构造函数
/// </summary>
public FTP()
{
strRemoteHost = "";
strRemotePath = "";
strRemoteUser = "";
strRemotePass = "";
strRemotePort = 21;
bConnected = false;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="remoteHost"></param>
/// <param name="remotePath"></param>
/// <param name="remoteUser"></param>
/// <param name="remotePass"></param>
/// <param name="remotePort"></param>
public FTP( string remoteHost, string remotePath, string remoteUser, string remotePass, int remotePort )
{
strRemoteHost = remoteHost;
strRemotePath = remotePath;
strRemoteUser = remoteUser;
strRemotePass = remotePass;
strRemotePort = remotePort;
Connect();
}
#endregion
#region 登陆
/// <summary>
/// FTP服务器IP地址
/// </summary>
public string RemoteHost
{
get
{
return strRemoteHost;
}
set
{
strRemoteHost = value;
}
}
/// <summary>
/// FTP服务器端口
/// </summary>
public int RemotePort
{
get
{
return strRemotePort;
}
set
{
strRemotePort = value;
}
}
/// <summary>
/// 当前服务器目录
/// </summary>
public string RemotePath
{
get
{
return strRemotePath;
}
set
{
strRemotePath = value;
}
}
/// <summary>
/// 登录用户账号
/// </summary>
public string RemoteUser
{
set
{
strRemoteUser = value;
}
}
/// <summary>
/// 用户登录密码
/// </summary>
public string RemotePass
{
set
{
strRemotePass = value;
}
}
/// <summary>
/// 是否登录
/// </summary>
public bool Connected
{
get
{
return bConnected;
}
}
#endregion
#region 链接
/// <summary>
/// 建立连接
/// </summary>
public void Connect()
{
socketControl = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(RemoteHost), strRemotePort);
// 链接
try
{
socketControl.Connect(ep);
}
catch(Exception)
{
throw new IOException("Couldn't connect to remote server");
}
// 获取应答码
ReadReply();
if(iReplyCode != 220)
{
DisConnect();
throw new IOException(strReply.Substring(4));
}
网络转载