public class CFTP
{
public TcpClient tcpClient = null;
public bool TcpConnected = false;
public bool TcpLoggedin = false;
private NetworkStream netStream = null;
public String Domain = null;
public int Port = 21;
public String User = null;
public String Pass = null;
public CFTP(String hostname, int port=21)
{
this.tcpClient = new TcpClient(hostname, port);
this.Domain = hostname;
this.Port = port;
String response = this.GetResponse("Hello");
if (response.Substring(0, 3) == "220")
{
this.TcpConnected = true;
}
else
{
this.TcpConnected = false;
throw new Exception("Es konnte keine Verbindung zum FTP-Server hergestellt werden!");
}
}
public void Close()
{
if (this.netStream != null)
{
this.netStream.Close();
this.netStream = null;
}
if (this.tcpClient != null)
{
this.tcpClient.Close();
this.tcpClient = null;
}
}
public bool Login(String user, String pass)
{
this.User = user;
this.Pass = pass;
if (this.TcpLoggedin == true)
{
//schon verbunden
return true;
}
if (this.TcpConnected == true)
{
this.GetResponse("USER " + this.User);
this.GetResponse("USER " + this.User);
String response = this.GetResponse("PASS " + this.Pass);
if (response.Substring(0, 3) == "230")
{
this.TcpLoggedin = true;
return true;
}
else
{
this.TcpLoggedin = false;
throw new Exception("Login oder Password falsch!");
}
}
return false;
}
public String GetResponse(String command)
{
this.netStream = this.tcpClient.GetStream(); /* TODO: Hier Socket Fehler ... */
if (this.netStream.CanWrite)
{
Byte[] sendBytes = Encoding.UTF8.GetBytes(command);
this.netStream.Write(sendBytes, 0, sendBytes.Length);
}
else
{
//cannot write
this.netStream.Close();
return null;
}
if (this.netStream.CanRead)
{
Byte[] bytes = new Byte[this.tcpClient.ReceiveBufferSize];
this.netStream.Read(bytes, 0, this.tcpClient.ReceiveBufferSize);
String returndata = Encoding.ASCII.GetString(bytes);
this.netStream.Close();
return returndata;
}
else
{
//cannot read
this.netStream.Close();
return null;
}
}