参看代码如下:
namespace AutoFtp
{
class FtpClient
{
//构造函数
public FtpClient()
{
}
//重载构造函数
public FtpClient(RichTextBox pRTB,string pIPaddress, string pStrRemoterPath, int pPort)
{
this.cRTB = pRTB;
strRemoterHost = TransitionDNStoIPaddress(pIPaddress);
strRemoterPort = pPort;
strRemoterPath = pStrRemoterPath;
//ShowExeMessage("ftp服务器初始化完成!");
ShowExeMessage("Initialize FTP Server parameters finished.");
}
private Socket s;
private RichTextBox cRTB;
//应答信息
private string strMsg;
private static int BLOCK_SIZE = 512;
private string strReply;
private int iReplyCode;
Byte[] buffer = new Byte[BLOCK_SIZE];
Encoding ASCII = Encoding.ASCII;
//传输模式
private TransferType trType;
#region 属性
//ftp登陆账号
private string strRemoterUser;
public string RemoteUser
{
get { return strRemoterUser; }
set { strRemoterUser = value; }
}
//ftp登陆密码
private string strRemoterPassWord;
public string RemoterPassWord
{
get { return strRemoterPassWord; }
set { strRemoterPassWord = value; }
}
//ftp登陆地址
private string strRemoterHost;
public string RemoterHost
{
get { return strRemoterHost; }
set { strRemoterHost = value; }
}
//ftp登陆端口
private int strRemoterPort;
public int RemoterPort
{
get { return strRemoterPort; }
set { strRemoterPort = value; }
}
//ftp服务器目录
private string strRemoterPath;
public string RemoterPath
{
get { return strRemoterPath; }
set { strRemoterPath = value; }
}
//ftp登陆状态
private bool _isConnected=false ;
public bool IsConnected
{
get { return _isConnected; }
set { _isConnected = value; }
}
#endregion
#region ftp操作方法
///
/// ftp登陆连接,确认账号密码。
///
///
public bool SocketConnect()
{
string _remoterHost = TransitionDNStoIPaddress(RemoterHost);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(_remoterHost), RemoterPort);
//使用IPV4建立Socket
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
s.Connect(endPoint);
ReadReply();
if (iReplyCode != 220)
{
DisConnect();
ShowExeMessage("FTP Error : " + strReply);
throw new IOException(strReply.Substring(4));
}
SendCommand("USER " + strRemoterUser);
AnalyseReply(331, 230, true, false);
if (iReplyCode != 230)
{
SendCommand("PASS " + strRemoterPassWord);
AnalyseReply(230, 202, true, false);
}
if (iReplyCode == 230)
{
IsConnected = true;
}
else
{
IsConnected = false;
ShowExeMessage("FTP Error : " + strReply);
throw new IOException(strReply.Substring(4));
}
if (strRemoterPath != "")
{
ChDir(strRemoterPath);
}
return true;
}
catch(Exception ex)
{
ShowExeMessage("Error : " + ex.ToString());
return false;
}
}
///
/// 关闭Socket连接
///
public void CloseSocketConnect()
{
if (s != null)
{
s.Close();
s = null;
}
IsConnected = false;
}
///
/// 打开服务器的目录
///
/// 服务器目录
public bool ChDir(string pDirName)
{
if (pDirName.Equals(".") || pDirName.Equals(""))
{
ShowExeMessage("FTP Folder Name invalid, please check : " + pDirName);
return false ;
}
if (!IsConnected)
{
SocketConnect();
}
SendCommand("CWD " + pDirName);
if (iReplyCode != 250)
{
SendCommand("CWD " + pDirName.Replace("//",""));
if (iReplyCode != 250)
{
ShowExeMessage("FTP Error : " + strReply);
return false;
}
}
this.strRemoterPath = pDirName;
return true;
//AnalyseReply(250, false, false);
//ShowExeMessage("当前目录:" + pDirName);
ShowExeMessage("Change Current Folder:" + pDirName);
}
///
/// 创建目录
///
/// 目录名
public void MkDir( string pDirName )
{
if( !IsConnected )
{
SocketConnect();
}
SendCommand( "MKD " + pDirName );
if( iReplyCode != 257 )
{
throw new IOException( strReply.Substring( 4 ) );
}
}
///
/// 获得文件列表
///
/// 文件名的匹配字符串
///
public string[] Dir(string pMask)
{
if (!IsConnected)
{
SocketConnect();
}
Socket socketData = CreateDataSocket();
SendCommand("NLST " + pMask);
if (!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226))
{
ShowExeMessage(strReply.Substring(4));
//throw new IOException(strReply.Substring(4));
}
strMsg = "";
while (true)
{
int iBytes = socketData.Receive(buffer, buffer.Length, 0);
strMsg += ASCII.GetString(buffer, 0, iBytes);
if (iBytes < buffer.Length)
{
break;
}
}
char[] seperator ={ '/n','/r'};
string[] strsFileList = strMsg.Split(seperator);
socketData.Close();
if (iReplyCode != 226)
{
ReadReply();
AnalyseReply(226, false, false);
}
return strsFileList;
}
#endregion
#region 上传和下载文件
///
/// 下载一批文件
///
/// 文件名的匹配字符串
/// 本地目录(不能以/结束)
public void Get(string pFileNameMask, string pFolder)
{
if (!IsConnected)
{
SocketConnect();
}
string[] strFiles = Dir(pFileNameMask);
foreach (string strFile in strFiles)
{
if (strFile != "")
{
//FileOperate.WriteLogFile("/n开始从ftp服务器下载文件:" + strFile + " ");
//ShowExeMessage("开始从ftp服务器下载文件:" + strFile);
ShowExeMessage("Start download files from FTP Server... Files : " + strFile);
Get(strFile, pFolder, strFile);
}
}
}
///
/// 下载一个文件
///
/// 下载的文件名
/// 本地目录(不能以/结束)
/// 保存本地文件名(为空时将文件名不变)
public void Get(string pRemoteFileName, string pFolder, string pLocalFileName)
{
if (!IsConnected)
{
SocketConnect();
}
SetTranferType(TransferType.Binary);
if (pLocalFileName.Equals(""))
{
pLocalFileName = pRemoteFileName;
}
//if (!File.Exists(pLocalFileName))
//{
// Stream st = File.Create(pLocalFileName);
// st.Close();
//}
FileStream outPut = new FileStream(pFolder + "//" + pLocalFileName,FileMode.Create);
Socket socketData = CreateDataSocket();
SendCommand("RETR " + pRemoteFileName);
if (!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226 || iReplyCode == 250))
{
ShowExeMessage("Error : " + strReply);
//throw new IOException(strReply.Substring(4));
}
while (true)
{
int iBytes = socketData.Receive(buffer, buffer.Length, 0);
outPut.Write(buffer, 0, iBytes);
if (iBytes <= 0)
{
break;
}
}
outPut.Close();
if (socketData.Connected)
{
socketData.Close();
}
if (!(iReplyCode == 226 || iReplyCode == 250))
{
ReadReply();
ShowExeMessage("Download file finished! Files : " + pRemoteFileName);
AnalyseReply(226, 250, false, false);
}
}
///
/// 上传一批文件
///
/// 本地目录(不得以/结束)
/// 文件名匹配字符可以包含*和?
public void Put(string pFolder, string pFileNameMask)
{
string[] strFiles = Directory.GetFiles(pFolder, pFileNameMask);
foreach (string strFile in strFiles)
{
ShowExeMessage("Start upload files to FTP Server ... Files : " + strFile + " ");
Put(strFile);
}
}
///
/// 上传一个文件
///
/// 上传的文件名字
public void Put(string pFileName)
{
if (!IsConnected)
{
SocketConnect();
}
Socket socketData = CreateDataSocket();
SendCommand("STOR " + Path.GetFileName(pFileName));
AnalyseReply(125, 150, false, false);
FileStream inPut = new FileStream(pFileName, FileMode.Open);
int iBytes = 0;
while ((iBytes = inPut.Read(buffer, 0, buffer.Length)) > 0)
{
socketData.Send(buffer, iBytes, 0);
}
inPut.Close();
if (socketData.Connected)
{
socketData.Close();
}
if (!(iReplyCode == 226 || iReplyCode == 250))
{
ReadReply();
AnalyseReply(226, 250, false, false);
ShowExeMessage("Upload files to FTP Server finished! Files : " + pFileName + " ");
}
}
///
/// 删除
///
/// 待删除文件名
public void Delete(string pStrFileName)
{
if (!IsConnected)
{
SocketConnect();
}
SendCommand("DELE " + pStrFileName);
if (iReplyCode != 250)
{
ShowExeMessage("FTP Error:" + strReply);
}
}
public void MoveToFile(string pOldFile, string pNewFile)
{
if (!IsConnected)
{
SocketConnect();
}
SendCommand("RNFR " + pOldFile);
if (iReplyCode != 350)
{
ShowExeMessage("FTP Error : " + strReply);
throw new IOException(strReply.Substring(4));
}
// 如果新文件名与原有文件重名,将覆盖原有文件
SendCommand("RNTO " + pNewFile);
if (iReplyCode != 250)
{
ShowExeMessage("FTP Error : " + strReply);
throw new IOException(strReply.Substring(4));
}
else
{
ShowExeMessage("Move files " + pOldFile + " TO " + pNewFile + " ");
}
}
#endregion
public enum TransferType { Binary, ASCII };
///
/// 设置传输模式
///
/// 传输模式
public void SetTranferType(TransferType pType)
{
if (pType == TransferType.Binary)
{
SendCommand("TYPE I");
}
else
{
SendCommand("TYPE A");
}
if (iReplyCode != 200)
{
throw new IOException(strReply.Substring(4));
}
else
{
trType = pType;
}
}
///
/// 获得传输模式
///
///
public TransferType GetTransferType()
{
return trType;
}
#region 内部函数
///
/// 退出ftp服务器
///
private void DisConnect()
{
if (s != null)
{
SendCommand("QUIT");
}
CloseSocketConnect();
}
///
/// 建立数据传输的Socket
///
///
private Socket CreateDataSocket()
{
SendCommand("PASV");
if (iReplyCode != 227)
{
throw new IOException(strReply.Substring(4));
}
int index1 = strReply.IndexOf('(');
int index2 = strReply.IndexOf(')');
string ipData = strReply.Substring(index1 + 1, index2 - index1 - 1);
int[] parts = new int[6];
int len = ipData.Length;
int partCount = 0;
string buf = "";
for (int i = 0; i < len && partCount <= 6; i++)
{
char ch = Char.Parse(ipData.Substring(i, 1));
if (Char.IsDigit(ch))
{
buf += ch;
}
else
{
if (ch != ',')
{
ShowExeMessage("FTP Error(Malformed PASV Reply): " + strReply);
throw new IOException("Malformed PASV Reply:" + strReply);
}
}
if (ch == ',' || i + 1 == len)
{
try
{
parts[partCount++] = Int32.Parse(buf);
buf = "";
}
catch (Exception ex)
{
ShowExeMessage("Error : " + "Malformed PASV Reply:" + strReply);
}
}
}
string ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];
int port = (parts[4] << 8) + parts[5];
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipAddress), port);
try
{
s.Connect(ep);
}
catch (Exception ex)
{
ShowExeMessage("Error : " + " Cannot connect to FTP server");
//throw new IOException("Can't connect to remote server");
}
return s;
}
///
/// 分析服务器返回代码
///
/// ftp应答代码
/// bool是否关闭Socket
/// bool是否退出ftp服务器
private void AnalyseReply(int pCode1, bool pCloseSocket, bool pDisconnect)
{
if (iReplyCode != pCode1)
{
if (pCloseSocket)
{
CloseSocketConnect();
}
if (pDisconnect)
{
DisConnect();
}
ShowExeMessage("FTP Error: " + strReply);
//throw new IOException(strReply.Substring(4));
}
}
///
/// 分析服务器返回代码
///
/// ftp应答代码
/// ftp应答代码
/// bool是否关闭Socket
/// bool是否退出ftp服务器
private void AnalyseReply(int pCode1, int pCode2, bool pCloseSocket, bool pDisconnect)
{
if (!(iReplyCode == pCode1 || iReplyCode == pCode2))
{
if (pCloseSocket)
{
CloseSocketConnect();
}
if (pDisconnect)
{
DisConnect();
}
ShowExeMessage("FTP Error: " + strReply);
}
}
///
/// 获取ftp服务器应答码
///
private void ReadReply()
{
strMsg = "";
strReply = ReadLines();
iReplyCode = Int32.Parse(strReply.Substring(0, 3));
}
///
/// 执行ftp命令
///
///
private void SendCommand(string pStrCommand)
{
byte[] cmdBytes = Encoding.GetEncoding("gb2312").GetBytes((pStrCommand + Environment.NewLine).ToCharArray()); // "/r/n"
s.Send(cmdBytes, cmdBytes.Length, 0);
ReadReply();
}
private string TransitionDNStoIPaddress(string pDNS)
{
IPAddress[] ip = Dns.GetHostAddresses(pDNS);
return ip[0].ToString();
}
///
/// 读取ftp服务器返回信息
///
///
private string ReadLines()
{
while (true)
{
int iBytes = s.Receive(buffer, buffer.Length, 0);
strMsg += ASCII.GetString(buffer, 0, iBytes);
if (iBytes < buffer.Length)
{
break;
}
}
char[] seperator ={ '/n' };
string[] mess = strMsg.Split(seperator);
if (strMsg.Length > 2)
{
strMsg = mess[mess.Length - 2];
}
else
{
strMsg = mess[0];
}
if (!strMsg.Substring(3, 1).Equals(" "))
{
return ReadLines();
}
return strMsg;
}
#endregion
private void ShowExeMessage(string pMessage)
{
cRTB.AppendText(pMessage + "/n");
cRTB.SelectionStart = pMessage.Length;
cRTB.ScrollToCaret();
FileOperate.WriteLogFile(pMessage);
}
}
}