Send a file via HTTP POST with C#

gabitoju picture gabitoju · Jul 15, 2009 · Viewed 255.4k times · Source

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!

Answer

Joshcodes picture Joshcodes · Oct 29, 2013

Using .NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet) there is an easier way to simulate form requests. Here is an example:

private async Task<System.IO.Stream> Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = await client.PostAsync(actionUrl, formData);
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return await response.Content.ReadAsStreamAsync();
    }
}