I’m trying to get the following code working:
string url = String.Format(@'SOMEURL'); string user = 'SOMEUSER'; string password = 'SOMEPASSWORD'; FtpWebRequest ftpclientRequest = (FtpWebRequest)WebRequest.Create(new Uri(url)); ftpclientRequest.Method = WebRequestMethods.Ftp.ListDirectory; ftpclientRequest.UsePassive = true; ftpclientRequest.Proxy = null; ftpclientRequest.Credentials = new NetworkCredential(user, password); FtpWebResponse response = ftpclientRequest.GetResponse() as FtpWebResponse;
This normally works, but for 1 particular server this gives an Error 500: Syntax not recognized. The Change Directory command is disabled on the problem server, and the site administrator told me that .NET issues a Change Directory command by default with all FTP connections. Is that true? Is there a way to disable that?
EDIT: When I login from a command line I am in the correct directory:
ftp> pwd
257 ‘/’ is current directory
I just tested this on one of our dev servers and indeed there is a CWD issued by the .NET FtpWebRequest:
This was without even specifying ‘/’ in the uri when creating the FtpWebRequest object.
If you debug or browse the source code, a class called ‘FtpControlStream’ comes into play. See call stack:
System.dll!System.Net.FtpControlStream.BuildCommandsList(System.Net.WebRequest req) Line 555 C# System.dll!System.Net.CommandStream.SubmitRequest(System.Net.WebRequest request = {System.Net.FtpWebRequest}, bool async = false, bool readInitalResponseOnConnect = true) Line 143 C# System.dll!System.Net.FtpWebRequest.TimedSubmitRequestHelper(bool async) Line 1122 + 0x13 bytes C# System.dll!System.Net.FtpWebRequest.SubmitRequest(bool async = false) Line 1042 + 0xc bytes C# System.dll!System.Net.FtpWebRequest.GetResponse() Line 649 C#There’s a method named BuildCommandsList() which is invoked. BuildCommandsList() builds a list of commands to send to the FTP server. This method has the following snippet of code:
Upon the first connection to the server m_PreviousServerPath is always null, the value of newServerPath is ‘/’ and is computed by a function named GetPathAndFileName() (invoked a few lines prior to this block of code). GetPathAndFileName() computes newServerPath as ‘/’ if no path is supplied or if ‘/’ is explicitly tacked on the end of the ‘ftp://….’ uri.
So this of course ultimately causes the CWD command to be added to the command pipeline because null != ‘/’.
In a nutshell unfortunately you can’t override this behaviour because it’s burned in the source.