Windows Forms: How to Upload a file to Web API from Windows Forms in C#

This post shows you How to upload files and submit form data to ASP.NET Core Web API using RestSharp in C# .NET Windows Forms Application.

First, You should create an ASP.NET Core project, then create a Web API to help you upload files to the web server. If you don't know how to Create a Web API in Visual Studio you can view this post: How to Upload files in ASP.NET Core Web API using C#.

Creating a new Windows Forms Application, then open your form designer.

Next, Drag the Label, TextBox and Button controls from your Visual Studio Toolbox into your form designer, then you can modify your layout as shown below.

upload files to web api from windows forms c#

Right-clicking on your project, then select Manage Nuget Packages => Search 'RestSharp' => then install it.

restsharpRestSharp is an open source library that helps you access Web API from .NET easy and work across platforms. It's a simple REST and HTTP API Client.

Adding a click event handler to the Browse button allows you to select the file name, then set the file name value to Text property of the TextBox control.

private void btnBrowse_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "All files|*.*" })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
            txtFileName.Text = ofd.FileName;
    }
}

Creating an UploadAsync method allows you to call Web API from c# windows forms to help you upload files to the web server.

private async Task<IRestResponse> UploadAsync(string fileName, string server)
{
    using (var fileStream = File.Open(fileName, FileMode.Open))
    {
        var client = new RestClient(server);
        var request = new RestRequest(Method.POST);
        using (MemoryStream memoryStream = new MemoryStream())
        {
            await fileStream.CopyToAsync(memoryStream);
            request.AddFile("file", memoryStream.ToArray(), fileName);
            request.AlwaysMultipartFormData = true;
            var response = await client.ExecuteTaskAsync(request);
            return response;
        }
    }
}

If you want to get value return from your web api, you can modify your upload method as shown below.

private async Task<string> UploadAsync(string fileName, string server)
{
    string value = null;
    using (var fileStream = File.Open(fileName, FileMode.Open))
    {
        var client = new RestClient(server);
        var request = new RestRequest(Method.POST);
        using (MemoryStream memoryStream = new MemoryStream())
        {
            await fileStream.CopyToAsync(memoryStream);
            request.AddFile("file", memoryStream.ToArray(), fileName);
            request.AlwaysMultipartFormData = true;

            var result = client.ExecuteAsync(request, (response, handle) =>
            {
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    dynamic json = JsonConvert.DeserializeObject(response.Content);
                    value = json.fileName;
                }
            });
        }
    }
    return value;
}

Finally, Add a click event handler to the Upload button allows you to upload files to the web server using web api.

private async void btnUpload_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(txtFileName.Text))
    {
        string url = "your url web api";
        IRestResponse restResponse = await this.UploadAsync(txtFileName.Text, url);
        if (restResponse.StatusCode == System.Net.HttpStatusCode.OK)
            MessageBox.Show("You have successfully uploaded the file", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

You can use the IRestRespone get value return when calling the web api from c# windows forms application.