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

Leave a Reply