Resolving application path in .dll Web, Console, WinForms and WPF applications

By | 2011.07.29

When sharing .dll’s between desktop applications and web applications finding the current application path can be troublesome.

For desktop applications you can usually just use the path of a loaded assembly (.exe or .dll) in the application directory. For web applications that won’t work since the .dll’s are copied to a temporary directory when the web application starts. This is caused by the ShadowCopy function of AppDomains and it enables us to overwrite web application binary files while server is running.

Here are some static methods to automatically resolve desktop apps to the .exe-directory and web apps to the web folder (you know, where the .aspx-files are). They work by replacing “~” with root directory. Method used for resolving varies by type, so a check to see if we are running as web application is used.

Usage

string appPath = ResolvePath("~");

Or use directly

string image = ResolvePath("~/Images/image1.jpg");

The code

// References required:
// System.Configuration
// System.Web

/// <summary>
/// Resolves path with ~ (root of current app) to application path.
/// </summary>
/// <param name="path">Path</param>
/// <returns>Physical path</returns>
public static string ResolvePath(string path)
{
    if (System.Web.HttpContext.Current == null)
        return ResolveAppPath(path);
    return ResolveWebPath(path);
}

/// <summary>
/// Resolves path with ~ (root of current app) to application path.
/// </summary>
/// <param name="path">Path</param>
/// <returns>Physical path</returns>
private static string ResolveAppPath(string path)
{
    return path.Replace("~", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/").Replace("/", "\\").Replace("\\\\", "\\");
}
/// <summary>
/// Resolves path with ~ (root of current web app) to physical application path.
/// </summary>
/// <param name="path">Path</param>
/// <returns>Physical path</returns>
private static string ResolveWebPath(string path)
{
    return path.Replace("~", System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "/").Replace("/", "\\").Replace("\\\\", "\\");
}
FacebookLinkedInTwitterOrkutDiggShare/Bookmark

Leave a Reply