日期:2014-05-19  浏览次数:21273 次

怎样用C#写一个测试FTP站点是否可以连接成功的程序?
只要最简单的连接是否成功的功能测试即可.
请给几个关键的代码,不胜感激.

------解决方案--------------------
只测试连接是否成功就话就用TcpClient类吧:
byte [] buf=new byte[1024];
TcpClient b = new TcpClient();
b.Connect(@ "127.0.0.1 ", 21); //IP及端口
b.Client.Receive(buf);

string s = Encoding.ASCII.GetString(buf);
if (s != " ")
MessageBox.Show(s);
else
MessageBox.Show( "error ");

------解决方案--------------------
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));
}

// 登陆
SendCommand( "USER "+strRemoteUser);
if( !(iReplyCode == 331 || iReplyCode == 230) )
{
CloseSocketConnect();//关闭连接
throw new IOException(strReply.Substring(4));
}
if( iReplyCode != 230 )
{
SendCommand( "PASS "+strRemotePass);
if( !(iReplyCode == 230 || iReplyCode == 202) )
{
CloseSocketConnect();//关闭连接
throw new IOException(strReply.Substring(4));
}
}
bConnected = true;

// 切换到目录
ChDir(strRemotePath);
}