Home
Map
MapPath: Virtual and Physical PathsUse MapPath in ASP.NET. MapPath returns physical paths and file locations.
ASP.NET
This page was last reviewed on Sep 26, 2022.
MapPath. We run the ASP.NET development server on a local machine. Its paths are not the same as they are on a server. The MapPath method handles this.
Method info. This is an important ASP.NET method. It resolves virtual paths and physical paths. For virtual paths, we have a "~" tilde, and MapPath handles this.
As a reminder, in ASP.NET the "~" tilde indicates the root of a virtual path. We need the tilde because otherwise ASP.NET can't figure out if a path is absolute or relative.
~/App_Data/Sample.xml ~/ ~/Map.txt
C:\Website\Files\Sample.xml C:\Website\Default.aspx C:\Website\Map.txt
Example. You can call MapPath in any C# file in your ASP.NET website. You may want to include the System.Web namespace first, but this is not required.
Note The Server.MapPath does the same thing as the Request.MapPath method. In this example, the two versions will do the same thing.
Note 2 There may be some differences in different usage scenarios, but in those cases a more detailed guide would be helpful.
Also The two methods (Server.MapPath and Request.MapPath) are interchangeable in most ASP.NET projects.
using System; using System.Web; /// <summary> /// This is an example code-behind file you can put in App_Code. /// It shows examples of using MapPath in code-behind. /// </summary> public class Example { public Example() { // This will locate the Example.xml file in the App_Data folder. // ... (App_Data is a good place to put data files.) string a = HttpContext.Current.Server.MapPath("~/App_Data/Example.xml"); // This will locate the Example.txt file in the root directory. // ... This can be used in a file in any directory in the application. string b = HttpContext.Current.Request.MapPath("~/Example.txt"); } }
A discussion. You can use the MapPath method to access many different paths on the server. If you are using a virtual shared host, there may be problems related to file permissions.
Note MapPath is simple and unless you have a typo in the argument, it will not cause you any problems.
Performance. MapPath performance was tested to be over 1000 times slower than a simple string append. It could be worthwhile to cache the paths with an appSettings cache.
appSettings
A summary. MapPath that resolves virtual paths to machine paths. It can work as a bridge between website-specific virtual paths, and a physical path that most .NET IO methods will require.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 26, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.