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.

public class UploadFIle  
{  
    public string FilePath { get; set; }  
    public string FileName { get; set; }  
    public long FileLength { get; set; }  
}  
public class UploadFIle  
{  
    public string FilePath { get; set; }  
    public string FileName { get; set; }  
    public long FileLength { get; set; }  
}

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.

public class UploadFileMultiparProvider : MultipartFormDataStreamProvider  
{  
    public UploadFileMultiparProvider(string rootPath) : base(rootPath) { }  

    public override string GetLocalFileName(HttpContentHeaders headers)  
    {  
        if (headers != null &&  
            headers.ContentDisposition != null)  
        {  
            return headers  
                .ContentDisposition  
                .FileName.TrimEnd('"').TrimStart('"');  
        }  

        return base.GetLocalFileName(headers);  
    }  
}

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.

public class MimeMultipart : ActionFilterAttribute  
{  
    public override void OnActionExecuting(HttpActionContext actionContext)  
    {  
        if (!actionContext.Request.Content.IsMimeMultipartContent())  
        {  
            throw new HttpResponseException(  
                new HttpResponseMessage(  
                    HttpStatusCode.UnsupportedMediaType)  
            );  
        }  
    }
}

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.

//Upload the File   
[MimeMultipart]  
public async Task<UploadFIle> Post()  
{  
    var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");  
    if (Request.Content.IsMimeMultipartContent())  
    {  
        var filePath = Request.Headers.GetValues("filePath").ToList();  
        string filepathfromclient = "";  
        if (filePath != null)  
        {  
            filepathfromclient = filePath[0];  
            uploadPath = uploadPath + filepathfromclient;  
        }
    }  
    if (!Directory.Exists(uploadPath))  
        Directory.CreateDirectory(uploadPath);  
    var multipartFormDataStreamProvider = new UploadFileMultiparProvider(uploadPath);  
    // Read the MIME multipart asynchronously   
    await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);  
    string _localFileName = multipartFormDataStreamProvider  
        .FileData.Select(multiPartData => multiPartData.LocalFileName).FirstOrDefault();  

    // Create response  
    return new UploadFIle  
    {  
        FilePath = _localFileName,
        FileName = Path.GetFileName(_localFileName),  
        FileLength = new FileInfo(_localFileName).Length  
    };  
}

WEB API getFileInfo Method

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

//api/ FileHandlingAPI/getFileInfo?Id=1  
[ActionName("get"), HttpGet]  
public IEnumerable<FilePath> getFileInfo(int Id)  
{  
    List<FilePath> files = new List<FilePath>();  
    var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");  

    DirectoryInfo dirInfo = new DirectoryInfo(uploadPath);  

    foreach (FileInfo fInfo in dirInfo.GetFiles())  
    {  
        files.Add(new FilePath() { Path = uploadPath, Filename = fInfo.Name, Length = fInfo.Length, IsDirectory = File.GetAttributes(uploadPath).HasFlag(FileAttributes.Directory) });  
    }  
    getAllSubfolderFiles(dirInfo, files);  
    return files.ToList();  
}

 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.  

#region Upload File  
//Upload File Button Click event  
private void btnUpload_Click(object sender, EventArgs e)  
{  

     Boolean uploadStatus = false;  
    DialogResult dr = this.openFileDialog1.ShowDialog();  
    if (dr == System.Windows.Forms.DialogResult.OK)  
    {  
        foreach (String localFilename in openFileDialog1.FileNames)  
        {  
            string url = "http://localhost:51389/api/FileHandlingAPI";  
            string filePath = @"\";  
            Random rnd = new Random();  
            string uploadFileName = "Imag"+rnd.Next(9999).ToString();  
            uploadStatus = Upload(url, filePath, localFilename, uploadFileName);  
        }  
    }  
    if (uploadStatus)  
    {  
        MessageBox.Show("File Uploaded");  
    }  
    else  
    {  
        MessageBox.Show("File Not Uploaded");  
    }  
}  
// filepath = @"Some\Folder\";  
// url= "http://localhost:51389/api/FileHandlingAPI";  
// localFilename = "c:\newProduct.jpg"   
//uploadFileName="newFileName"  
bool Upload(string url, string filePath, string localFilename, string uploadFileName)  
{  
    Boolean isFileUploaded = false;  

    try  
    {  
        HttpClient httpClient = new HttpClient();  

        var fileStream = File.Open(localFilename, FileMode.Open);  
        var fileInfo = new FileInfo(localFilename);  
        UploadFIle uploadResult = null;  
        bool _fileUploaded = false;  

        MultipartFormDataContent content = new MultipartFormDataContent();  
        content.Headers.Add("filePath", filePath);  
        content.Add(new StreamContent(fileStream), "\"file\"", string.Format("\"{0}\"", uploadFileName  + fileInfo.Extension)  
                );  

        Task taskUpload = httpClient.PostAsync(url, content).ContinueWith(task =>  
        {  
            if (task.Status == TaskStatus.RanToCompletion)  
            {  
                var response = task.Result;  

                if (response.IsSuccessStatusCode)  
                {  
                    uploadResult = response.Content.ReadAsAsync<UploadFIle>().Result;  
                    if (uploadResult != null)  
                        _fileUploaded = true;  
                }
            }  
            fileStream.Dispose();  
        });  

        taskUpload.Wait();  
        if (_fileUploaded)  
            isFileUploaded = true;
        httpClient.Dispose();  

    }  
    catch (Exception ex)  
    {  
        isFileUploaded = false;  
    }  
    return isFileUploaded;  
}  

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

#region FileInformation  
//Get File List  
private void btnFileList_Click(object sender, EventArgs e)  
{  
    string URI = "http://localhost:51389/api/FileHandlingAPI/getFileInfo?Id=1";  
    GetFileInformation(URI);  
}  

   
private async void GetFileInformation(string url)  
{  
    List<ServerFileInformation> filesinformation = new List<ServerFileInformation>();  
    using (var client = new HttpClient())  
    {  
        using (var response = await client.GetAsync(url))  
        {  
            if (response.IsSuccessStatusCode)  
            {  
                var fileJsonString = await response.Content.ReadAsStringAsync();  

             dataGridView1.DataSource = JsonConvert.DeserializeObject<ServerFileInformation[]>(fileJsonString).ToList();   
            }  
        }  
    }  
}  
#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.

#region Download File  
//Download File  
private void btnDownload_Click(object sender, EventArgs e)  
{  
    string url = "http://localhost:51389/Uploads/";  
    string downloadFileName = txtFileName.Text.Trim();  
    string downloadPath = Application.StartupPath + @"\Downloads\";  

    if (!Directory.Exists(downloadPath))  
        Directory.CreateDirectory(downloadPath);  

    Boolean isFileDownloaded = Download(url, downloadFileName, downloadPath);  
    if (isFileDownloaded)  
    {  
        MessageBox.Show("File Downloaded");  
    }  
    else  
    {  
        MessageBox.Show("File Not Downloaded");  
    }  
}  

// url = http://localhost:51389/Uploads/"    
// downloadFileName = "new2.jpg"   
// downloadPath =  Application.StartupPath + "/Downloads/";  
bool Download(string url, string downloadFileName, string downloadFilePath)  
{  
    string downloadfile = downloadFilePath + downloadFileName;  
    string httpPathWebResource = null;  
    Boolean ifFileDownoadedchk = false;  
    ifFileDownoadedchk = false;  
    WebClient myWebClient = new WebClient();  
    httpPathWebResource = url + downloadFileName;  
    myWebClient.DownloadFile(httpPathWebResource, downloadfile);  

    ifFileDownoadedchk = true;  

    return ifFileDownoadedchk;  
}

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.


Similar Articles