views:

538

answers:

3

The following code is intended to retrieve a file via FTP. However, I'm getting an error with it.

serverPath = "ftp://x.x.x.x/tmp/myfile.txt";

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);

request.KeepAlive = true;
request.UsePassive = true;
request.UseBinary = true;

request.Method = WebRequestMethods.Ftp.DownloadFile;                
request.Credentials = new NetworkCredential(username, password);

// Read the file from the server & write to destination                
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))            
using (StreamWriter destination = new StreamWriter(destinationFile))
{
    destination.Write(reader.ReadToEnd());
    destination.Flush();
}

The error is:

The remote server returned an error: (550) File unavailable (e.g., file not found, no access)

The file definately does exist on the remote machine and I am able to perform this ftp manually (i.e. I have permissions). Can anyone tell me why I might be getting this error?

A: 

not sure if it fixes your error, but shouldn't all of your using statements have brackets so the object is not disposed of before you try to access it in your next using statment?

using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))  
{          
using (StreamWriter destination = new StreamWriter(destinationFile))
{
    destination.Write(reader.ReadToEnd());
    destination.Flush();
}
}
}
}
derek
The braces are optional I think and the statement block keeps nesting until it gets to the braces that are there. (in a similar fashion to nested ifs)
Martin Smith
+3  A: 

This paragraph from the FptWebRequest class reference might be of interest to you:

The URI may be relative or absolute. If the URI is of the form "ftp://contoso.com/%2fpath" (%2f is an escaped '/'), then the URI is absolute, and the current directory is /path. If, however, the URI is of the form "ftp://contoso.com/path", first the .NET Framework logs into the FTP server (using the user name and password set by the Credentials property), then the current directory is set to /path.

Frank Bollack
A: 

What happens if you set UsePassive to false? I never got any server working using passive mode..

Roy
That would generally cause a time out error in my experience as it tries to use a port blocked by the firewall.
Martin Smith
Well that is as far as my knowledge goes, the rest of the code seems fine to me.
Roy