views:

121

answers:

2

Hi,

I need to upload a file in C# using an httpwebrequest. I don't need to post any form data. It's a scheduled task that will run once a night and upload a file to a server. It will need to set the credentials. I've seen some examples and I'm not really sure what's happening in them and they all include form data. Would it be possible for some to share some sample code with an explanation as to why I'm doing what I'm doing so I can learn it. I would really appreciate it.

+4  A: 

If you don't need to include form-data, then you can just send as the body of a post:

using(WebClient client = new WebClient()) {
    client.Credentials = new NetworkCredential(username, password);
    client.UploadFile(uri, path);
}

or if you need to use a different http-method (perhaps "PUT"):

using(WebClient client = new WebClient()) {
    client.Credentials = new NetworkCredential(username, password);
    client.UploadFile(uri, "PUT", path);
}
Marc Gravell
+1 Once again - too fast!
Andrew Hare
+1 Ditto @Andrew
Quintin Robinson
(re "with an explanation" - by the very nature of using `WebClient`, I don't think there is much unnecessary code left to explain... feel free to ask, though)
Marc Gravell
A: 

WebClient.UploadFile allows you to upload not only using HTTP POST but also using FTP connection. Maybe the FTP option could be easier for your architecture...

rossoft