Saturday, 31 January 2015

ASP.NET C# - How to specify File Path

If you want to access a file with in an ASP.NET Application, you should specify the relative path to the file from the application root.
For example your file name is "StockConfig.xml" and its placed within a "Configs" folder.
Now you need to load the file; use the below code for this.
Server.MapPath("~/Configs/StockConfig.xml")
example usage:
xDoc.Load(Server.MapPath("~/Configs/StockConfig.xml"));
Here Server.MapPath, returns the physical path corresponding to the relative path you mentioned.
"~" specifies the application root. So any path you mention following "~" is relative to the application root folder.

In case you are trying to access "Server.MapPath()" from a class library, you will need to "Add Reference" System.Web assembly to your class library and use the code as below:
System.Web.HttpContext.Current.Server.MapPath("~/StockConfig.xml")

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete