In this article I will explain with an example, how to use WebClient in Windows Forms (WinForms) Application.
This article will illustrate how to call an API using the DownloadString method of the WebClient class in Windows Forms (WinForms) Application.
 
 
ASPSnippets Test API
The following API will be used in this article.
The API returns the following JSON.
[
   {
      "CustomerId":1,
      "Name":"John Hammond",
      "Country":"United States"
   },
   {
      "CustomerId":2,
      "Name":"Mudassar Khan",
      "Country":"India"
   },
   {
      "CustomerId":3,
      "Name":"Suzanne Mathews",
      "Country":"France"
   },
   {
      "CustomerId":4,
      "Name":"Robert Schidner",
      "Country":"Russia"
   }
]
 
 
Form Design
The following Form consists of a Multiline TextBox control.
Using WebClient in Windows Forms using C# and VB.Net
 
 
Namespaces
C#
You will need to import the following namespace.
using System.Net;
 
VB.Net
Imports System.Net
 
 
Calling the API using WebClient class
Inside the Form Load event handler, first the JSON string is downloaded from an API using DownloadString method of the WebClient class.
Note: SecurityProtocol needs to be set to TLS 1.2 (3072) in order to call an API.
 
Finally, the JSON string is assigned to the TextBox control.
C#
private void Form1_Load(object sender, EventArgs e)
{
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    string json = (new WebClient()).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json");
    txtJson.Text = json;
}
 
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ServicePointManager.Expect100Continue = True
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    Dim json As String = (New WebClient()).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json")
    txtJson.Text = json
End Sub
 
 
Screenshot
Using WebClient in Windows Forms using C# and VB.Net
 
 
Downloads