Consume Web API In Winform For File Handling

In this article, we will see in details, how to consume Web API in Windows Form for uploading file to Web server,  get the list of file information from Server folder, and download the file from Server using C# Windows application.

For this demo, we will create one Web API project and one WinForm application.

In Web API project, we will create a Controller for uploading files to web server and to return the file details list with, File Name, File Path and File length.

From WinForm application, user can upload the files to the Web Server using MultipartFormDataContent; display the file information to Data GridView with Filename, File path and length from web server; and download the file from web server to the local client winform root folder using WebClient.

WEB API

Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles. It has the following four methods as Get/Post/Put and Delete where -

  • Get is used to request for the data. (Select)
  • Post is used to create a data. (Insert)
  • Put is used to update the data.
  • Delete is used to delete the data.

Prerequisites

  • Visual Studio 2015: You can download it from here.
  • Microsoft.AspNet.WebApi.Client installed for Winform application using NuGet Packages.
  • Newtonsoft.json installed for Winform application using NuGet Packages.

Code Part

Step 1 Create Web API application.

Open Visual Studio 2015 and click New >> Project >> Web >> ASP.NET Web Application. Enter your project name and click OK.

C# Windows application

Next, select Empty project and check on Web API checkbox. Click OK.

C# Windows application

Step 2 Creating Class file in Models

Create a Class for file details model  - Right click Models folder > Click "Add new class".


C# Windows application

Enter the file name as “UploadFile” and create a class file.

C# Windows application

Add the below properties for file handling.

  1. public class UploadFIle  
  2.     {  
  3.         public string FilePath { get; set; }  
  4.         public string FileName { get; set; }  
  5.         public long FileLength { get; set; }  
  6.     }  
  7. public class UploadFIle  
  8.     {  
  9.         public string FilePath { get; set; }  
  10.         public string FileName { get; set; }  
  11.         public long FileLength { get; set; }  
  12.     }  

Create a MultipartProvider Class for uploading file  - Right click Models folder > Click "Add new class".


C# Windows application

Enter the file name as “UploadFileMultiparProvider” and create a class file.

C# Windows application

Create the MultipartProvider class for uploading files.

  1. public class UploadFileMultiparProvider : MultipartFormDataStreamProvider  
  2.     {  
  3.         public UploadFileMultiparProvider(string rootPath) : base(rootPath) { }  
  4.   
  5.         public override string GetLocalFileName(HttpContentHeaders headers)  
  6.         {  
  7.             if (headers != null &&  
  8.                 headers.ContentDisposition != null)  
  9.             {  
  10.                 return headers  
  11.                     .ContentDisposition  
  12.                     .FileName.TrimEnd('"').TrimStart('"');  
  13.             }  
  14.   
  15.             return base.GetLocalFileName(headers);  
  16.         }  
  17.     }  

Create a MimeMultipart Filter Class for uploading file - Right click Models folder > Click "Add new class".


C# Windows application

Enter the file name as “MimeMultipart” and create a class file.

  1. public class MimeMultipart : ActionFilterAttribute  
  2.     {  
  3.         public override void OnActionExecuting(HttpActionContext actionContext)  
  4.         {  
  5.             if (!actionContext.Request.Content.IsMimeMultipartContent())  
  6.             {  
  7.                 throw new HttpResponseException(  
  8.                     new HttpResponseMessage(  
  9.                         HttpStatusCode.UnsupportedMediaType)  
  10.                 );  
  11.             }  
  12.         }  

Step 3 Create Web API Controller

Right click the Controllers folder and click Add > Controller.

C# Windows application

Select Controller from left side and select Web API Controller Class.

C# Windows application

Give your Controller a name as “andlingAPIController” and click "Add".

C# Windows application

Create File Upload Post Method

Using Web API post method, we can upload the file to the web server. In this method, we get the file using post method and upload the file to the web server Uploads folder.

  1. //Upload the File   
  2.         [MimeMultipart]  
  3.         public async Task<UploadFIle> Post()  
  4.         {  
  5.             var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");  
  6.   
  7.   
  8.             if (Request.Content.IsMimeMultipartContent())  
  9.             {  
  10.   
  11.                 var filePath = Request.Headers.GetValues("filePath").ToList();  
  12.                 string filepathfromclient = "";  
  13.   
  14.   
  15.                 if (filePath != null)  
  16.                 {  
  17.                     filepathfromclient = filePath[0];  
  18.                     uploadPath = uploadPath + filepathfromclient;  
  19.                 }  
  20.   
  21.   
  22.             }  
  23.   
  24.             if (!Directory.Exists(uploadPath))  
  25.                 Directory.CreateDirectory(uploadPath);  
  26.   
  27.             var multipartFormDataStreamProvider = new UploadFileMultiparProvider(uploadPath);  
  28.   
  29.             // Read the MIME multipart asynchronously   
  30.             await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);  
  31.   
  32.             string _localFileName = multipartFormDataStreamProvider  
  33.                 .FileData.Select(multiPartData => multiPartData.LocalFileName).FirstOrDefault();  
  34.   
  35.             // Create response  
  36.             return new UploadFIle  
  37.             {  
  38.                 FilePath = _localFileName,  
  39.   
  40.                 FileName = Path.GetFileName(_localFileName),  
  41.   
  42.                 FileLength = new FileInfo(_localFileName).Length  
  43.             };  
  44.         }  

WEB API getFileInfo Method

Using this get method, we return all the file information as a JSON result.

  1. //api/ FileHandlingAPI/getFileInfo?Id=1  
  2.         [ActionName("get"), HttpGet]  
  3.         public IEnumerable<FilePath> getFileInfo(int Id)  
  4.         {  
  5.             List<FilePath> files = new List<FilePath>();  
  6.             var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");  
  7.   
  8.             DirectoryInfo dirInfo = new DirectoryInfo(uploadPath);  
  9.   
  10.             foreach (FileInfo fInfo in dirInfo.GetFiles())  
  11.             {  
  12.                 files.Add(new FilePath() { Path = uploadPath, Filename = fInfo.Name, Length = fInfo.Length, IsDirectory = File.GetAttributes(uploadPath).HasFlag(FileAttributes.Directory) });  
  13.             }  
  14.   
  15.   
  16.   
  17.             getAllSubfolderFiles(dirInfo, files);  
  18.   
  19.   
  20.   
  21.   
  22.             return files.ToList();  
  23.         }  

When we run the Web API application, we can see the file details in JSON, as shown below.

C# Windows application

Our Web API part is complete. Now, we can create a Winform application to consume the Web API and upload/download the files from web server to our local machine.

Step 4 Create Winform application

Open Visual Studio 2015. Click New >> Project >> Visual C# >> Windows >> select Windows Forms Application. Enter your project name and click OK.

C# Windows application

Step 5 Install Packages

Install Microsoft.AspNet.WebApi.Client and Newtonsoft.json using NuGet Package Manager.

Right click the solution and click on "Manage NuGet Packages" and install the above two files.

C# Windows application

C# Windows application

C# Windows application

Step 6 Design the Windows form like below

Add 3 buttons - one for File Browsing and uploading to the web server, second one for downloading the file from web server, and a third one to get File List to collect all the file information from webserver and binding it to grid.

C# Windows application

Browse/Upload File Button Click

In upload file button click, we call the method as upload and pass the Web API URL to upload the file to the web server file path.

  1. #region Upload File  
  2.     //Upload File Button Click event  
  3.     private void btnUpload_Click(object sender, EventArgs e)  
  4.     {  
  5.   
  6.          Boolean uploadStatus = false;  
  7.         DialogResult dr = this.openFileDialog1.ShowDialog();  
  8.         if (dr == System.Windows.Forms.DialogResult.OK)  
  9.         {  
  10.             foreach (String localFilename in openFileDialog1.FileNames)  
  11.             {  
  12.                 string url = "http://localhost:51389/api/FileHandlingAPI";  
  13.                 string filePath = @"\";  
  14.                 Random rnd = new Random();  
  15.                 string uploadFileName = "Imag"+rnd.Next(9999).ToString();  
  16.                 uploadStatus = Upload(url, filePath, localFilename, uploadFileName);  
  17.             }  
  18.         }  
  19.         if (uploadStatus)  
  20.         {  
  21.             MessageBox.Show("File Uploaded");  
  22.         }  
  23.         else  
  24.         {  
  25.             MessageBox.Show("File Not Uploaded");  
  26.         }  
  27.     }  
  28.   
  29.   
  30.     // filepath = @"Some\Folder\";  
  31.     // url= "http://localhost:51389/api/FileHandlingAPI";  
  32.     // localFilename = "c:\newProduct.jpg"   
  33.     //uploadFileName="newFileName"  
  34.     bool Upload(string url, string filePath, string localFilename, string uploadFileName)  
  35.     {  
  36.         Boolean isFileUploaded = false;  
  37.   
  38.         try  
  39.         {  
  40.             HttpClient httpClient = new HttpClient();  
  41.   
  42.             var fileStream = File.Open(localFilename, FileMode.Open);  
  43.             var fileInfo = new FileInfo(localFilename);  
  44.             UploadFIle uploadResult = null;  
  45.             bool _fileUploaded = false;  
  46.   
  47.             MultipartFormDataContent content = new MultipartFormDataContent();  
  48.             content.Headers.Add("filePath", filePath);  
  49.             content.Add(new StreamContent(fileStream), "\"file\"", string.Format("\"{0}\"", uploadFileName  + fileInfo.Extension)  
  50.                     );  
  51.   
  52.             Task taskUpload = httpClient.PostAsync(url, content).ContinueWith(task =>  
  53.             {  
  54.                 if (task.Status == TaskStatus.RanToCompletion)  
  55.                 {  
  56.                     var response = task.Result;  
  57.   
  58.                     if (response.IsSuccessStatusCode)  
  59.                     {  
  60.                         uploadResult = response.Content.ReadAsAsync<UploadFIle>().Result;  
  61.                         if (uploadResult != null)  
  62.                             _fileUploaded = true;  
  63.   
  64.                     }  
  65.                       
  66.                 }  
  67.   
  68.                 fileStream.Dispose();  
  69.             });  
  70.   
  71.             taskUpload.Wait();  
  72.             if (_fileUploaded)  
  73.                 isFileUploaded = true;  
  74.       
  75.             httpClient.Dispose();  
  76.   
  77.         }  
  78.         catch (Exception ex)  
  79.         {  
  80.             isFileUploaded = false;  
  81.         }  
  82.   
  83.   
  84.         return isFileUploaded;  
  85.     }  
  86.  
  87.     #endregion  

Get File List Button Click

In GetFileInformation method, we pass the Web API URL to get all the file details from web server. From Web API, we get the file information as JSON result. In the Winform application, we have used Jsonconvert to deserialize and bind the result to the DataGridView.

  1.     #region FileInformation  
  2.         //Get File List  
  3.         private void btnFileList_Click(object sender, EventArgs e)  
  4.         {  
  5.             string URI = "http://localhost:51389/api/FileHandlingAPI/getFileInfo?Id=1";  
  6.             GetFileInformation(URI);  
  7.         }  
  8.   
  9.            
  10.         private async void GetFileInformation(string url)  
  11.         {  
  12.             List<ServerFileInformation> filesinformation = new List<ServerFileInformation>();  
  13.             using (var client = new HttpClient())  
  14.             {  
  15.                 using (var response = await client.GetAsync(url))  
  16.                 {  
  17.                     if (response.IsSuccessStatusCode)  
  18.                     {  
  19.                         var fileJsonString = await response.Content.ReadAsStringAsync();  
  20.   
  21.                      dataGridView1.DataSource = JsonConvert.DeserializeObject<ServerFileInformation[]>(fileJsonString).ToList();   
  22.                     }  
  23.                 }  
  24.             }  
  25.         }  
  26. #endregion  

Download Button Click

In Download method, we pass the Web API URL with file name to download, and local computer save location. Here, we have used the Winfrom root folder to save the file from web server to our local machine.

  1. #region Download File  
  2.     //Download File  
  3.     private void btnDownload_Click(object sender, EventArgs e)  
  4.     {  
  5.         string url = "http://localhost:51389/Uploads/";  
  6.         string downloadFileName = txtFileName.Text.Trim();  
  7.         string downloadPath = Application.StartupPath + @"\Downloads\";  
  8.   
  9.         if (!Directory.Exists(downloadPath))  
  10.             Directory.CreateDirectory(downloadPath);  
  11.   
  12.         Boolean isFileDownloaded = Download(url, downloadFileName, downloadPath);  
  13.         if (isFileDownloaded)  
  14.         {  
  15.             MessageBox.Show("File Downloaded");  
  16.         }  
  17.         else  
  18.         {  
  19.             MessageBox.Show("File Not Downloaded");  
  20.         }  
  21.     }  
  22.   
  23.     // url = http://localhost:51389/Uploads/"    
  24.     // downloadFileName = "new2.jpg"   
  25.     // downloadPath =  Application.StartupPath + "/Downloads/";  
  26.     bool Download(string url, string downloadFileName, string downloadFilePath)  
  27.     {  
  28.         string downloadfile = downloadFilePath + downloadFileName;  
  29.         string httpPathWebResource = null;  
  30.         Boolean ifFileDownoadedchk = false;  
  31.         ifFileDownoadedchk = false;  
  32.         WebClient myWebClient = new WebClient();  
  33.         httpPathWebResource = url + downloadFileName;  
  34.         myWebClient.DownloadFile(httpPathWebResource, downloadfile);  
  35.   
  36.         ifFileDownoadedchk = true;  
  37.   
  38.         return ifFileDownoadedchk;  
  39.     }  

Reference Link

https://chsakell.com/2015/06/07/web-api-file-uploading-desktop-and-web-client/

Conclusion

Build and run the application. Publish the Web API to your web server and update the Web API URL in the Winform. You can test your application now. From the attached zipped file, you can download both, Winform and Web API, source files.

Up Next
    Ebook Download
    View all
    Learn
    View all