views:

3508

answers:

3

Hi everyone, I've been searching and reading around to that and couldn't fine anything really useful.

I'm writing an small C# win app that allows user to send files to a web server, not by FTP, but by HTTP using POST. Think of it like a web form but running on a windows application.

I have my HttpWebRequest object created using something like this HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest and also set the Method, ContentType and ContentLength properties. But thats the far I can go.

This is my piece of code:

        HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
        req.KeepAlive = false;
        req.Method = "POST";
        req.Credentials = new NetworkCredential(user.UserName, user.UserPassword);
        req.PreAuthenticate = true;
        req.ContentType = file.ContentType;
        req.ContentLength = file.Length;
        HttpWebResponse response = null;

        try
        {
            response = req.GetResponse() as HttpWebResponse;
        }
        catch (Exception e) {}

So my question is basically how can I send a fie (text file, image, audio, etc) with C# via HTTP POST.

Thanks!

+4  A: 

To send the raw file only:

using(WebClient client = new WebClient()) {
    client.UploadFile(address, filePath);
}

If you want to emulate a browser form with an <input type="file"/>, then that is harder. See this answer for a multipart/form-data answer.

Marc Gravell
(you can of course add headers / credentials / etc as normal)
Marc Gravell
Thanks, I've used it with something simple and I't worked. Now, as you say, I do need to emulate a browser input file, somethig like this <intput type="file" name"userFile"/>.
gabitoju
+1  A: 

You neeed to write your file to the request stream:

using (var reqStream = req.GetRequestStream()) 
{    
    reqStream.Write( ... ) // write the bytes of the file
}
Pop Catalin
A: 

Thanks all for the replys, they help me a lot.

I also found this that also help me.

Thank you all.

gabitoju