Навигация

Итоги года

Другие ссылки


Реклама

Счётчики


FtpWebRequest: The remote server returned an error: (500) Syntax error, command unrecognized

12.08.2009 Среда 19:34

I am wokring on a project now that involves transfering data by FTP. I use standard .Net functionality to do FTP'ing — System.Net.FtpWebRequest class. Everything works fine while I am running single isolated requests to the FTP server. But when I start a batch processing that quickly sends massive requests to the server (like "list files in a FTP directory", "upload a file", "download a file", "delete a file") I start seeing the following error, which occurs sporadically:

The remote server returned an error: (500) Syntax error, command unrecognized.
at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
at System.Net.FtpWebRequest.RequestCallback(Object obj)
at System.Net.CommandStream.InvokeRequestCallback(Object obj)
at System.Net.CommandStream.Abort(Exception e)
at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)
at System.Net.FtpWebRequest.GetResponse()
at MyCoolProgram.DownloadFileFromFtp(String fileName) in C:\MyCoolProgram\FtpHelper.cs:line 97

The exception is happening in this code:

FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);
uploadRequest.ReadWriteTimeout = 30000;
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;
uploadRequest.Credentials = new NetworkCredential(myLogin, myPassword);
requestStream = uploadRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
response = (FtpWebResponse)uploadRequest.GetResponse(); // <— here occurs the exception

The reason is somewhat strange inner workings of the .Net FTP library. For some reason it sometimes decides to send USER command to the server between downloads. If it did it always, I'd see this error on each request. But it doesn't do it always, it does it SOMETIMES. Weird enough. But, anyway. The solution is to re-use the NetworkCredential instance between the calls. That is, create an instance of the NetworkCredential class once, and re-use it for each FtpWebRequest created.

I found this solution here. There's more elaborated info on the topic.