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

Suggested Videos
Part 17 - Data bind asp.net dropdownlist with data from the database
Part 18 - Binding an asp.net dropdownlist with an XML file
Part 19 - Mapping virtual path to physical path using Server.MapPath method

In Part 19 of asp.net video series, we discussed about Server.MapPath() method. In this video, we will continue with a practical application of this method. Please watch Part 19 first, if haven't already done so.



Drag and drop a DropDownList control onto PageInElectronicsFolder.aspx webform. Copy and paste the following code in the code behind file.
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("../../Data/Countries/Countries.xml"));
DropDownList1.DataTextField = "CountryName";
DropDownList1.DataValueField = "CountryId";
DropDownList1.DataSource = DS;
DropDownList1.DataBind();



C:\SampleWeb\SampleWeb is the root directory for the sample asp.net web application that we used in the Demo. To get to this root directory we are passing ../../ to the Server.MapPath() method as shown below.
DS.ReadXml(Server.MapPath("../../Data/Countries/Countries.xml"));

The number of double dots, that you use, depends on how deep you are in the folder hierarchy. To avoid confusion, if any time you want to navigate to the root directory of the application, it is better to use ~(tilde) character as shown below.
DS.ReadXml(Server.MapPath("~/Data/Countries/Countries.xml"));

Tilde(~) symbol resolves to the root application directory, no matter how deep you are in the folder hierarchy. This is the advantage of using ~(tilde), over ..(2 Dots). The following code would work from any folder in our application.
DS.ReadXml(Server.MapPath("~/Data/Countries/Countries.xml"));

Where as, the following code will only work from folders, that are 2 levels deeper relative to the root directory of the application.
DS.ReadXml(Server.MapPath("../../Data/Countries/Countries.xml"));

5 comments:

  1. Hi Venkat. Thank you so much for providing such nice video tutorials.Can you please post tutorials on Grid view.

    ReplyDelete
    Replies
    1. Hi, thank you very much for the feedback. Sure, I will record a video series on working with GridView control as soon as I can. If you want to receive email alerts when new videos, are uploaded, please subscribe to my youtube channel using the link below.
      http://youtube.com/kudvenkat

      Link for asp.net, c#, and sql server video tutorial playlists
      ASP.NET, C#, and SQL Server Video Tutorial

      Delete
  2. You are simply awesome Venkat. You are a natural teacher. Its so easy to understand your tutorials. Please keep up the good works.

    ReplyDelete
  3. May God bless you and fullfill all your dreams...

    ReplyDelete
  4. You are simply awesome Sir.

    ONLY SUCH A GREAT BLOG ON .Net existing on the internet

    ReplyDelete

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