In this article I will explain with an example, how to download XML file from URL in ASP.Net using C# and VB.Net.
First, the XML file will be downloaded from the URL using WebClient class and then will be saved in a Folder (Directory) in ASP.Net using C# and VB.Net.
XML File URL
The following XML file will be used in this article.
<?xml version="1.0" standalone="yes"?>
<Customers>
<Customer>
<CustomerId>1</CustomerId>
<Name>John Hammond</Name>
<Country>United States</Country>
</Customer>
<Customer>
<CustomerId>2</CustomerId>
<Name>Mudassar Khan</Name>
<Country>India</Country>
</Customer>
<Customer>
<CustomerId>3</CustomerId>
<Name>Suzanne Mathews</Name>
<Country>France</Country>
</Customer>
<Customer>
<CustomerId>4</CustomerId>
<Name>Robert Schidner</Name>
<Country>Russia</Country>
</Customer>
</Customers>
Namespaces
You will need to import the following namespace.
C#
VB.Net
Downloading XML File from URL in ASP.Net
Inside the Page Load event handler, the XML 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.xml", @"D:\Files\Customers.xml");
}
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.xml", "D:\Files\Customers.xml")
End Sub
Screenshot
The downloaded XML file
Downloads