read entire file and post to webserver in csharp

Here's an example code snippet which reads an entire file and posts its contents to a web server using HttpClient in C#:

main.cs
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

public static async Task PostFileToWebServer(string filePath, Uri uri)
{
    try
    {
        using (var client = new HttpClient())
        {
            using (var fileStream = File.OpenRead(filePath))
            {
                using (var content = new StreamContent(fileStream))
                {
                    var response = await client.PostAsync(uri, content);

                    if (response.IsSuccessStatusCode)
                    {
                        // File was successfully posted to web server
                    }
                    else
                    {
                        // Handle unsuccessful response
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        // Handle exception
    }
}
871 chars
35 lines

The above code uses HttpClient to send an HTTP POST request to the specified URI with the contents of the specified file as the request body. The StreamContent class is used to wrap the file stream so that the request body can be read from it. The PostAsync method sends the HTTP POST request and returns a HttpResponseMessage which contains the response from the web server. The IsSuccessStatusCode property of the HttpResponseMessage is used to check whether the response was successful.

gistlibby LogSnag