How to Consume Web API In Winforms For File Handling in C#
By FoxLearn 7/18/2024 8:13:41 AM 15.47K
How to use Web API In Winform For File Handling in C#
First, You need to know how to create a Web API to help you upload files to a 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 drag and drop the Label, TextBox and Button controls from the Visual Studio Toolbox to your form designer. You can create a simple UI that allows you to select a file, then upload it to web server via web api in c#.
Creating an UploadAsync method allows you to upload the file to the web server by calling web api controller in c# windows forms application.
You can use HttpClient
class from System.Net.Http
to make HTTP requests.
// c# winforms access web api private async Task<HttpResponseMessage> UploadAsync(string fileName, string server) { using (var fileStream = File.Open(txtFileName.Text, FileMode.Open)) { using (MemoryStream memoryStream = new MemoryStream()) { await fileStream.CopyToAsync(memoryStream); using (MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent()) { multipartFormDataContent.Add(new ByteArrayContent(memoryStream.ToArray()), "file", txtFileName.Text); using (var client = new HttpClient()) { var response = await client.PostAsync(server, multipartFormDataContent).ConfigureAwait(false); return response; } } } } }
Adding a click event handler to the Browse button allows you to open a file dialog box, then select the file and update the file name to 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; } }
Finally, Add a click event handler to the Upload button allows you to call the UploadAsync method to upload files from your hard drive to the web server using web api in c# windows forms application.
// c# upload file to web server in windows forms application private async void btnUpload_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtFileName.Text)) { string url = "http://localhost:11122/api/file/upload"; HttpResponseMessage responseMessage = await this.UploadAsync(txtFileName.Text, url); if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK) MessageBox.Show("You have successfully uploaded the file", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
You can easily upload images or any other files to the web server using the UploadAsync method to upload files via web api in c#.
Through this example, i hope so you can easily call and consume a Web API within your C# Windows Forms Application.