Tuesday, July 3, 2012

Get The Correct Assembly Path

For a typical application, the referenced supporting assemblies would have the same location as the main executable. If you need to get the application's location from one of the referenced assemblies, you may use the following function:

Note: To make sure the path is get from the correct assembly, the GetAssemblyPath function must exist in the assembly's source code itself (instead of putting into another helper assembly). As such, please paste the following code at whenever you need it.

/// <summary>
/// Gets current assembly path.
/// </summary>
/// <returns>Assembly path</returns>
internal static string GetAssemblyPath()
{
    Assembly assembly = Assembly.GetEntryAssembly();

    if (assembly == null)
        assembly = Assembly.GetCallingAssembly();
    if (assembly == null)
        assembly = Assembly.GetExecutingAssembly();

    if (assembly == null)
        return "";
    else
        return Path.GetDirectoryName((new Uri(assembly.CodeBase)).LocalPath);
}

If you find this post helpful, would you buy me a coffee?


No comments:

Post a Comment