s

how upload a file from a console application written in C# to the server using web api edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 03 October 2020 | 7022

In this article, we will look at how to upload a file from a console application to the server using web API. You might be familiar with code on how to transfer a file from a web form to a web API, If you already wrote the code for the web API you don't have to modify it, you only have to write the code to transfer the file from the client to the server. In this post, we will write code for both the server and the client. First, let's write the web API code which receives the file from the console application.

Web API Code

You can create either a web API application or MVC application. In my application, I have added a method called Upload file to receive the files from the server. Check the code below. This function receives the files as well as a parameter called userId from the console application.

[HttpPost]
public ActionResult UploadFile(String userId)
{
    if (Request.Files.Count > 0)
    {
        var file = Request.Files[0];
        file.SaveAs(Server.MapPath("/Files/")   file.FileName);
    }
    return Json("success");
}


Console Application

Here is the console application code which will transfer the files to the web api. We use the HTPPClient class to send files and parameters to the server. Please not best practice for using HttpClient is that it should be instantiated once and it should be re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This might cause a SocketException error.

class Program
{
    static void Main(string[] args)
    {
        UploadFile();
    }

    public static void UploadFile()
    {
        string file = @"C:\Works\songs.txt";
        if (!File.Exists(file))
        {
            return;
        }
        using (var form = new MultipartFormDataContent())
        {
            var Content = new ByteArrayContent(File.ReadAllBytes(file));
            Content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
            form.Add(Content, "file", Path.GetFileName(file));
            form.Add(new StringContent("muruganad"), "userId");
            using (HttpClient client = new HttpClient())
            {
                var response = client.PostAsync(@"http://localhost:50436/Home/UploadFile", form);
                response.Wait();
            }
        }
    }
}