Search code examples
c#ftpwindows-server-2012

FtpWebResponse error 550 when closing stream on dowloading (Windows Server 2012)


I have read a lot of messages and questions about hte 550 problem with FtpWebResponse. But the issue I have encountered is pretty specific. The first time I am trying to download a file, I do not have any problems. The response gives back a stream which I am saving to a file.

But when I try to invoke this method for the second time for the same file, I'm checking if the file already exists on my PC, and if yes, I am trying to close the stream and dispose the response. The problem is that the response and stream throws a 550 error on the close method.

In Wireshark, just after message "Data connection already open; transfer starting (125)" I get the 550 answer for the Windows Server 2012. How it is possible to read the file once, and than not being able to just close the stream?

The code sequence is something like this:

var request = GetNewDownloadRequest(uri);
try
{
   response = GetFTP(request);
}
catch (WebException e)
{
   throw;
}
Stream stream = response.GetResponseStream();
if (!File.Exists(localPath))
{
   SaveToFile(stream);
}

stream.Close();
response.Close();
stream = File.OpenRead(localPath);

Sending a request without using it for download allows me to check if the file is also present on the FTP server.

I have also compared downloads - in my app and in Chrome. The only difference was that Chrome uses CWD command in between, so I used the MSDN solution with a similar issue, but in the end it did not help.

The last thing I am thinking about is that I am grabbing a stream from response only to close it. Can I close a stream without even reading a byte of it? Can I resolve a stream just to close it?


Solution

  • My current solution is that you cannot close both the stream from response or the response the moment you have invoked them. The only way to clean everything up is to copy the entire stream to (for example) MemoryStream, and than you can close both.