In this article I will explain with an example, how to download XML file from Folder (Directory) in ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
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 Schidner</Name>
       <Country>Russia</Country>
    </Customer>
</Customers>
 
 
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, 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 as string and then stored in a variable.
Finally, the variable i.e. XML file contents are sent to the Client Browser as string using the Content function.
Note: The Content function sends the data to the Response similar to Response.Write function.
 
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        //Set the Response properties.
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/xml";
        Response.AddHeader("content-disposition", "attachment; filename=Customers.xml");
 
        //Read the XML file contents as String.
        string xml = System.IO.File.ReadAllText(Server.MapPath("~/XML/Customers.xml"));
        return Content(xml);
    }
}
 
 
View
There is no programming required inside the View and hence this section is skipped.
 
 
Screenshot
Download XML File in ASP.Net MVC
 
 
Downloads