6

I'm trying to send a file using ftp. I have the following code:

string server = "x.x.x.x";  // Just the IP Address 

FileStream stream = File.OpenRead(filename);
byte[] buffer = new byte[stream.Length];

WebRequest request = WebRequest.Create("ftp://" + server);
request.Method = WebRequestMethods.Ftp.UploadFile;            
request.Credentials = new NetworkCredential(username, password);

Stream reqStream = request.GetRequestStream(); // This line fails
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();

But when I run it, I get the following error:

The requested URI is invalid for this FTP command.

Please can anyone tell me why? Am I using this incorrectly?

2
  • 3
    How does server look like ? Commented May 5, 2010 at 11:29
  • @thelost - inappropriate question... he cannot tell us the ftp... it may be public... you could use a temp string to check out if the complete server URI is as it should be. The rest looks good. Commented May 5, 2010 at 11:32

2 Answers 2

10

I think you need to specify the path and filename you're uploading too, so I think it should be either of:

WebRequest request = WebRequest.Create("ftp://" + server + "/");

WebRequest request = WebRequest.Create("ftp://" + server + "/filename.ext");
Sign up to request clarification or add additional context in comments.

2 Comments

The first gave the same error, but once the file name was specified, it worked fine - thanks
@ho1 Thanks. FYI: Incase if you are uploading to a folder then it should be like WebRequest request = WebRequest.Create("ftp://" + server + "//foldername" +"/filename.ext");
0

When I had to use ftp method, I had to set some flags on request object, without it the function did not work:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath);
request.KeepAlive = true/false;
request.UsePassive = true/false;
request.UseBinary = xxx;

These flags depend on the server, if you have no access to the server then you cannot know what to use here, but you can test and see what works in your configuration.

And file name is probably missing at the end of URI, so that the server knows where to save uploaded file.

2 Comments

Those flags do not appear to be properties of the WebRequest object
@pm_2: sorry, I forgot to add one line where request object is created. It is actually an object of FtpWebRequest type. I updated the answer to show it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.