How to send arbitrary FTP commands in C#
Asked Answered
D

4

8

I have implemented the ability to upload, download, delete, etc. using the FtpWebRequest class in C#. That is fairly straight forward.

What I need to do now is support sending arbitrary FTP commands such as

quote SITE LRECL=132 RECFM=FB
or 
quote SYST

Here's an example configuration straight from our app.config:

<!-- The following commands will be executed before any uploads occur -->
<extraCommands>
     <command>quote SITE LRECL=132 RECFM=FB</command>
</extraCommands>

I'm still researching how to do this using FtpWebRequest. I'll probably try WebClient class next. Anyone can point me in the right direction quicker? Thanks!

UPDATE: I've come to that same conclusion, as of .NET Framework 3.5 FtpWebRequest doesn't support anything except what's in WebRequestMethods.Ftp.*. I'll try a third party app recommended by some of the other posts. Thanks for the help!

Demodulation answered 23/2, 2010 at 19:35 Comment(1)
Did you try Rebex FTP with those commands? did it work well?Auscultation
T
9

I don't think it can be done with FtpWebRequest... The only way to specify a FTP command is through the Method property, and the documentation states :

Note that the strings defined in the WebRequestMethods.Ftp class are the only supported options for the Method property. Setting the Method property to any other value will result in an ArgumentException exception.

SITE and SYST are not among the predefined options, so I guess you're stuck...

Don't waste time to try the WebClient class, it will give you even less flexibility than FtpWebRequest.

However, there are plenty of third-party FTP implementation, open source or commercial, and I'm pretty sure some of them can handle custom commands...

Toothpick answered 23/2, 2010 at 21:17 Comment(0)
S
8

The FtpWebRequest won't help you as Thomas Levesque has said in his answer. You can use some third party solutions or the following, simplified TcpClient based code which I have refactored from an answer written in Visual Basic:

public static void SendFtpCommand()
{
    var serverName = "[FTP_SERVER_NAME]";
    var port = 21;
    var userName = "[FTP_USER_NAME]";
    var password = "[FTP_PASSWORD]"
    var command = "SITE CHMOD 755 [FTP_FILE_PATH]";

    var tcpClient = new TcpClient();
    try
    {
        tcpClient.Connect(serverName, port);
        Flush(tcpClient);

        var response = TransmitCommand(tcpClient, "user " + userName);
        if (response.IndexOf("331", StringComparison.OrdinalIgnoreCase) < 0)
            throw new Exception(string.Format("Error \"{0}\" while sending user name \"{1}\".", response, userName));

        response = TransmitCommand(tcpClient, "pass " + password);
        if (response.IndexOf("230", StringComparison.OrdinalIgnoreCase) < 0)
            throw new Exception(string.Format("Error \"{0}\" while sending password.", response));

        response = TransmitCommand(tcpClient, command);
        if (response.IndexOf("200", StringComparison.OrdinalIgnoreCase) < 0)
            throw new Exception(string.Format("Error \"{0}\" while sending command \"{1}\".", response, command));
    }
    finally
    {
        if (tcpClient.Connected)
            tcpClient.Close();
    }
}

private static string TransmitCommand(TcpClient tcpClient, string cmd)
{
    var networkStream = tcpClient.GetStream();
    if (!networkStream.CanWrite || !networkStream.CanRead)
        return string.Empty;

    var sendBytes = Encoding.ASCII.GetBytes(cmd + "\r\n");
    networkStream.Write(sendBytes, 0, sendBytes.Length);

    var streamReader = new StreamReader(networkStream);
    return streamReader.ReadLine();
}

private static string Flush(TcpClient tcpClient)
{
    try
    {
        var networkStream = tcpClient.GetStream();
        if (!networkStream.CanWrite || !networkStream.CanRead)
            return string.Empty;

        var receiveBytes = new byte[tcpClient.ReceiveBufferSize];
        networkStream.ReadTimeout = 10000;
        networkStream.Read(receiveBytes, 0, tcpClient.ReceiveBufferSize);

        return Encoding.ASCII.GetString(receiveBytes);
    }
    catch
    {
        // Ignore all irrelevant exceptions
    }

    return string.Empty;
}

You can expect the following flow while getting through the FTP:

220 (vsFTPd 2.2.2)
user [FTP_USER_NAME]
331 Please specify the password.
pass [FTP_PASSWORD]
230 Login successful.
SITE CHMOD 755 [FTP_FILE_PATH]
200 SITE CHMOD command ok.
Sodomy answered 29/9, 2015 at 15:19 Comment(0)
R
3

You can try our Rebex FTP component:

// create client and connect 
Ftp client = new Ftp();
client.Connect("ftp.example.org");
client.Login("username", "password");

// send SITE command
// note that QUOTE and SITE are ommited. QUOTE is command line ftp syntax only.
client.Site("LRECL=132 RECFM=FB");

// send SYST command
client.SendCommand("SYST");
FtpResponse response = client.ReadResponse();
if (response.Group != 2) 
  ; // handle error 

// disconnect 
client.Disconnect();
Rarotonga answered 24/2, 2010 at 17:5 Comment(0)
S
-5

Use sendCommand("SITE LRECL=242 BLKSIZE=0 RECFM=FB");

Semicircle answered 10/6, 2010 at 10:29 Comment(1)
This is very unhelpful because no information is provided. What is "sendCommand" is it a 3rd party library, does it have something to do with FtpWebRequest???Syringa

© 2022 - 2024 — McMap. All rights reserved.