Windows Forms: How to Upload Image To Server in C#

This post shows you How to Upload Image To Web Server in C# Windows Forms Application.

Dragging PictureBox, Button, TextBox controls from the Visual Studio toolbox into your form designer, then design a simple UI allows you to display image to PictureBox, show image path to TextBox and upload image to server in c# as shown below.

c# winform upload image to server

How to call web api post method from windows application in c#

Right-clicking on your project, then select Manage Nuget Packages. Next, Search 'RestSharp', then download and install it.

c# restsharp

You should create a web api allows you to upload file to web server. If you don't know how to create a web api you can view this post How to Upload files in ASP.NET Core Web API using C#.

Adding a click event handler to the Upload button allows you to upload an image to server in c#.

private async void btnUpload_Click(object sender, EventArgs e)
    //c# open file dialog with image filters
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.png)|*.jpg; *.jpeg; *.gif; *.bmp; *.png" })
        if (ofd.ShowDialog() == DialogResult.OK)
            //c# display image in picture box  
            pictureBox1.Image = new Bitmap(ofd.FileName);
            //c# show image file path  
            txtFileName.Text = ofd.FileName;
            //c# upload image to web server
            using (var fileStream = File.Open(ofd.FileName, FileMode.Open))
                var client = new RestClient("http://localhost:11122/api/file/upload");
                var request = new RestRequest(Method.POST);
                using (MemoryStream memoryStream = new MemoryStream())
                    await fileStream.CopyToAsync(memoryStream);
                    request.AddFile("file", memoryStream.ToArray(), ofd.FileName);
                    request.AlwaysMultipartFormData = true;
                    var response = await client.ExecuteAsync(request);
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                        dynamic json = JsonConvert.DeserializeObject(response.Content);
                        string fileName = json.fileName;
                        //Handling your code

If you want to get the filename when the file is uploaded to the server. You need to install RestSharp.Newtonsoft.Json from Manage Nuget  Packages in your Visual Studio.

c# restsharp newtonsoft json

Through this post, i hope so you can understand how to upload image to server c# windows application via c# web api upload file with model core.