Be nice to nerds. Chances are you'll end up working for one. --Bill Gates
Welcome to my blog about software development and the Microsoft stack.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more
Share/Print this page:

Subscribe for news, updates and more:

PathHelper - Convert File and Folder Paths and URLs in an ASP.NET Application

Absolute, virtual, physical and application relative paths and their conversion

By steve on February 13, 2007.
Updated on January 22, 2012.
Viewed 22,506 times (15 times today).
Article AttributesArticle AttributesArticle TypesLanguagesTechnologies
Has DownloadsHas ImagesSnippetC#ASP.NET

An important concept in managing path conversions is the application path. An ASP.NET application resides in a folder at either the root of a website or a subfolder. In order to have a portable web application, you don't want to hard code URLs in the application. All URLs should be essentially application relative.

But this means we need to programmatically determine the application path. URLs should be coded as follows:

Portable URLs

Contents
string url = PathHelper.AppPath + "folder/page.aspx";

The PathHelper.AppPath Method

Contents
/// <summary>
/// The virtual application path:
/// "/myapp/"
/// "/apps/myapp/"
/// "/"
/// </summary>
public static string AppPath
{
	get
	{
		// get the regular application path
		string path = HttpContext.Current.Request.ApplicationPath;

		// ensure a trailing slash...
		if (path == "")
			return "/";
		if (path[path.Length-1] != '/')
			path += "/";
		return path;
	}
}

Listing of Various Conversion Methods in PathHelper class

Using the PathHelper Class - Get path type

Contents
string path = TextBox1.Text.Trim();

// test whether path is a physical path
bool isPhysical = PathHelper.IsPhysicalPath(path);

// test whether path is an absolute URL path
bool isAbsolute = PathHelper.IsAbsolutePath(path);

// test whether path is a virtual URL path
bool isVirtual = PathHelper.IsVirtualPath(path);

// test whether path is application relative 
bool isApplication = PathHelper.IsApplicationPath(path);

Sample output of PathHelper demo in the download

Credits

Contents

Credit goes to Matt Bell for the initial version of this class.

Back to Top

User Comments (0)

Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.