In this article I will explain with an example, how to use
DownloadFile function of
WebClient class in C# and VB.Net.
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"
}
]
Namespaces
You will need to import the following namespace.
C#
using System.Net;
VB.Net
Imports System.Net
Using DownloadFile function of WebClient class
Inside the Page_Load event handler, first the Security Protocol is set.
Then, the
JSON file is downloaded from the URL using
DownloadFile method of the
WebClient class.
DownloadFile method
It accepts the following two parameters:
address – The URL of the file to be downloaded.
fileName – Path of the Folder (Directory) where the file will be downloaded.
C#
protected void Page_Load(object sender, EventArgs e)
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
WebClient webClient = new WebClient();
webClient.DownloadFile("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json", @"D:\Files\Customers.json";)
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
Dim webClient As WebClient = New WebClient()
webClient.DownloadFile("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json", "D:\Files\Customers.json")
End Sub
Screenshot
The downloaded JSON file
Downloads