How to Upload a file to Web API in C#

By FoxLearn 11/15/2024 8:52:54 AM   19.06K
To upload files and submit form data to an ASP.NET Core Web API using RestSharp in a C# Windows Forms application, you can follow these steps.

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#.

How to Upload file to Rest API in C# Windows Forms

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

Next, Drag and drop 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#

To upload a file to a REST API using C# Windows Forms, you can use the HttpClient class to send HTTP requests or use the RestSharp library.

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

restsharp

RestSharp 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.

// c# openfiledialog
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.

// c# web api upload file
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.

// c# web api upload file
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;
}

How to call Web API POST method from Windows application in C#

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

// how to use API in c# windows form
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, IRestRespone helps you consume Web API In Winform for file handling upload to the Web Server using MultipartFormDataContent

If you don't want to use RestSharp you can also use HttpClient to handle upload file to web server.

Creating a FileUploader class to handle upload file via web api in c# as shown below.

public class FileUploader
{
    readonly HttpClient _httpClient;

    public FileUploader()
    {
        _httpClient = new HttpClient();
        // Set base URL of your REST API
        _httpClient.BaseAddress = new Uri("https://yourwebapi.com/");
        // Optionally, set other configurations such as headers, timeouts, etc.
    }

    public async Task<bool> UploadFileAsync(string filePath)
    {
        try
        {
            // Read file contents into a byte array
            byte[] fileBytes = File.ReadAllBytes(filePath);

            // Create a ByteArrayContent object from the file bytes
            ByteArrayContent content = new ByteArrayContent(fileBytes);

            // Send a POST request to the API endpoint where you want to upload the file
            HttpResponseMessage response = await _httpClient.PostAsync("upload", content);

            // Check if the request was successful
            if (response.IsSuccessStatusCode)
            {
                // File uploaded successfully
                return true;
            }
            else
            {
                //You can handle error: Failed to upload file. Status code: response.StatusCode
                return false;
            }
        }
        catch (Exception ex)
        {
            // Handle exception
            // "Error uploading file: " + ex.Message
            return false;
        }
    }
}

Add HttpClient to your project and make sure you have System.Net.Http namespace included in your project. You can do this by adding a reference to System.Net.Http in your project.

Adding click event handler to upload button

// c# upload file to web server in windows forms
private async void UploadButton_Click(object sender, EventArgs e)
{
    string filePath = "path_to_your_file"; // Replace with the path to your file
    FileUploader uploader = new FileUploader();

    // Call the method to upload the file asynchronously
    bool uploadResult = await uploader.UploadFileAsync(filePath);

    if (uploadResult)
    {
        MessageBox.Show("File uploaded successfully!");
    }
    else
    {
        MessageBox.Show("Failed to upload file.");
    }
}

Don't forget to replace "https://yourwebapi.com/" with the base URL of your REST API and "upload" with the endpoint where you want to upload the file