Skip to content

Instantly share code, notes, and snippets.

@tslothorst
Created December 6, 2021 14:52
Show Gist options
  • Save tslothorst/0d2b46889c2c40ddb299cdc8223741cb to your computer and use it in GitHub Desktop.
Save tslothorst/0d2b46889c2c40ddb299cdc8223741cb to your computer and use it in GitHub Desktop.
Get your application path in C#

Finding out where your application runs in C#

Sometimes you might need to know where your application is running, for instance if you want to open a file relative to that position. With desktop apps this is more straightforward but web applications run within IIS and any attempt to navigate to a relative path will fail because you start out within a directory from the IIS webserver.

Here is quick way to find out where you're application is running:

public static string GetFullApplicationPath()
{
  return HttpRuntime.AppDomainAppVirtualPath != null ? HttpRuntime.AppDomainAppPath : Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}

This method works for web applications and desktop applications. It tests if it is a web application and if so it returns the AppDomainAppPath property. Else it returns the Assembly.location property.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment