Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Mapping virtual path to physical path using Server.MapPath method - Part 19

Suggested Videos
Part 16 - DropDownList in asp.net
Part 17 - Data bind asp.net dropdownlist with data from the database
Part 18 - Binding an asp.net dropdownlist with an XML file

In this video we will discuss about Server.MapPath() method. This method returns the physical path for a given virtual path. This method can be used in several different ways, depending on the characters that we use in the virtual path. Let's understand this with an example.



1. Create an asp.net web application in C:\ and name it SampleWeb.
2. Right click on the SampleWeb project in solution explorer and add a new webform and name it PageInRootDirectory.aspx
3. Add a new folder to the project and name it Categories.
4. Right click on the Categories folder, and add another folder. name it Electronics
5. Add a webform to the Electronics folder and name it PageInElectronicsFolder.aspx
6. At this point, right click on the web application project and add a new folder. Name it Data.
7. Add a sub folder to Data, and name it Countries
8. Right click on the Countries folder and add an XML file. Name it Countries.xml.
9. Copy and paste the following in Countries.xml file.
<?xml version="1.0" encoding="utf-8" ?>
<Countries>
  <Country>
    <CountryId>101</CountryId>
    <CountryName>India</CountryName>
  </Country>
  <Country>
    <CountryId>102</CountryId>
    <CountryName>US</CountryName>
  </Country>
  <Country>
    <CountryId>103</CountryId>
    <CountryName>Australia</CountryName>
  </Country>
  <Country>
    <CountryId>104</CountryId>
    <CountryName>UK</CountryName>
  </Country>
</Countries>



If you are following along with me, at this stage, the solution explorer should look as shown below.


Copy and paste the following code in PageInElectronicsFolder.aspx.cs
Response.Write(". returns " + Server.MapPath(".") + "<br/>");
Response.Write(".. returns " + Server.MapPath("..") + "<br/>");
Response.Write("~ returns " + Server.MapPath("~") + "<br/>");

Running this page would produce the following output.
. returns C:\SampleWeb\SampleWeb\Categories\Electronics
.. returns C:\SampleWeb\SampleWeb\Categories
~ returns C:\SampleWeb\SampleWeb

From the output, it should be clear that
Server.MapPath(".") returns the current physical directory of the page that you are running
Server.MapPath("..") returns the parent pysical directory of the page that you are running
Server.MapPath("~") returns the physical path of the root directory of the application

1 comment:

  1. Thanks for the great article, It really help me regarding better use of Server.MapPath feature in asp .net

    ReplyDelete

It would be great if you can help share these free resources