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
1 |
string appPath = ResolvePath("~"); |
Or use directly
1 |
string image = ResolvePath("~/Images/image1.jpg"); |
The code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// 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("\\\\", "\\"); } |