views:

242

answers:

1

I get the following message back when trying to retrieve a file using TCPClient and RAW FTP:

"425 Failed to establish connection."

I connect using :

using (TcpClient client = new TcpClient("ServerName", 21))
        using (NetworkStream stream = client.GetStream())
        using (StreamReader reader = new StreamReader(stream))
        using (StreamWriter writer = new StreamWriter(stream))
        {

and then I login to the server fine using USER ** and PASS * i manage to change to the correct directory using CWD //, as mentioned this all works fine and i get the expected response messages.

However when the following code executes the message mentioned above is all i receive.

            lineToSend = "PASV";
            Program.logger.Add("Sending to server: " + lineToSend, 1);
            writer.WriteLine(lineToSend);
            while (!stream.DataAvailable)
            {
                Program.logger.Add(stream.DataAvailable.ToString(), 1);
                Program.logger.Persist();
                Thread.Sleep(1000);

            }
            lineWeRead = reader.ReadLine();
            Program.logger.Add("Received from server: " + lineWeRead, 1);
            Program.logger.Persist();

            lineToSend = "RETR file.txt";
            Program.logger.Add("Sending to server: " + lineToSend, 1);
            writer.WriteLine(lineToSend);
            while (!stream.DataAvailable)
            {
                Program.logger.Add(stream.DataAvailable.ToString(), 1);
                Program.logger.Persist();
                Thread.Sleep(1000);
            }

            Program.logger.Add("Loop Exited: " + stream.DataAvailable.ToString(), 1);
            Program.logger.Persist();
            lineWeRead = reader.ReadLine();
            Program.logger.Add("Received from server: " + lineWeRead, 1);
            Program.logger.Persist();

I am fairly new to C#.NET and have been asked specifically to use this method of connecting and not the httpWebRequest.

The file I am trying to receive is a text file containing only "Get this message" but will be bigger when used.

Any help is much appreciated.

Thanks Ash

+2  A: 

You might want to read up on the FTP protocol. There is not one connection, but two involved. I don't see a data connection anywhere in your code, which is probably where the 425 is coming from.

I agree with the comment -- unless this is a homework-style question, please don't reinvent the wheel here. FTP stinks and this problem has been solved.

Joe
+1 If you really plan to use TcpClient, you need an extra Socket or TcpListener object for FTP active mode, or another TcpClient or Socket object for FTP passive mode.
Lex Li