In this article I will explain with an example, how to download XML file from Folder (Directory) in ASP.Net using C# and VB.Net.
XML File
Following is the XML file named Customers consisting of records of Customers stored in the project folder.
<?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 SchCustomerIdner</Name>
<Country>Russia</Country>
</Customer>
</Customers>
HTML Markup
The following HTML Markup consists of a Button.
The Button has been assigned an OnClick event handler
<asp:Button ID="btnDownloadXML" Text="Download XML" runat="server" OnClick="DownloadXML" />
Downloading the XML File
When the Download Button is clicked, the following event handler is executed.
Inside this event handler, following properties set are the Response class.
1. ContentType – It informs the Browser about the file type. In this case it is XML.
2. Content-Disposition – It is a response header indicating, the download file is an attachment and allows setting the file name.
Once the Response properties are set, the XML file contents are read.
Finally, using the WriteFile method of the Response class, the File is written to the Response using the Path of the XML file and the file is downloaded.
C#
protected void DownloadXML(object sender, EventArgs e)
{
//Set the Response properties.
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/xml";
Response.AddHeader("application/xml", "attachment; filename=Customers.xml");
Response.WriteFile(Server.MapPath("~/Customers.xml"));
Response.Flush();
Response.End();
}
VB.Net
Protected Sub DownloadXML(sender As Object, e As EventArgs)
'Set the Response properties.
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/xml"
Response.AddHeader("application/xml", "attachment; filename=Customers.xml")
Response.WriteFile(Server.MapPath("~/Customers.xml"))
Response.Flush()
Response.End()
End Sub
Screenshot
Demo
Downloads