Finding the path of an ASP.NET webapp

If you’re trying to generate a filename that’s relative to the root of your webapp, the easiest thing to do is use the Page.MapPath() method.

If you want to load a file in the root directory of your webapp, you’d use the MapPath() method in the following way:

dataset1.ReadXml(MapPath("xmlfile.xml"));

If this isn’t what you’re trying to do, there’s a lot more path environment information available:

Request.ApplicationPath – path of the requested page from the root of the webapp url (ie. /aspnet/tips). Only accessible from objects that can access the request object like pages, user controls and web controls.

Request.PhysicalApplicationPath – absolute path of the requested page on the file system (ie. c:inetpubwwwrootblogaspnettips). Again only accessible from objects that can access the request object.

AppDomain.CurrentDomain.BaseDirectory – the path to the directory that the current code is running from. In the case of web applications it returns the directory where the aspx files are located.

System.Reflection.Assembly.GetExecutingAssembly().Location – the place in the temporary asp.net files where your page is being run

System.Environment.CurrentDirectory – the directory in the shell which is the current directory

System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName – the filename of the process that’s currently executing. It returns the path to aspnet_wp.exe for web applications

Environment.GetCommandLineArgs()[0] – the first argument if you ran your app as a command line program, the name and path of the program. Returns the path to aspnet_wp.exe for web applications

Posted on 29 Sep 04 by Helen Emerson (last updated on 29 Sep 04).
Filed under ASP.NET