A coworker and I ran into a problem yesterday - we were trying to re-use an assembly from a WinForms app, in a WebService and ran into this code:
Directory.SetCurrentDirectory(Application.StartupPath);
The problem with this, is that it uses the Application static class, which is part of System.Windows.Forms - and we're in a web service now, not a WinForms app. So, after some headache and thought, we tried to use this:
Assembly.GetExecutingAssembly().Location
That doesn't work well, either, because in the web, it gives you the ShadowCopy location of the assembly, not the original location of the assemblies. A little more thought, and a few hours later, we finally came up with this:
private static string GetBinFolder()
{
AppDomain appDomain = AppDomain.CurrentDomain;
string binFolder;
if (appDomain.RelativeSearchPath != null && appDomain.RelativeSearchPath != string.Empty )
binFolder = Path.Combine(appDomain.BaseDirectory, appDomain.RelativeSearchPath);
else
binFolder = appDomain.BaseDirectory;
return binFolder;
}
The AppDomain.BaseDirectory will give you the root folder that the application is being run from - no matter what type of app you are in; windows or web. This is perfect for Windows because it alone gives us the folder that the code is running from and lets us find the assembly we need. The RelativeSearchPath is important for the web - it gives us the "bin" folder where our assemblies live. So a simple check to see if there is a relative search path (it returns null in a standard WinForms app) and combine the two if there are, otherwise just get the base directory, and we now have our folder that the assemblies are located in, so we can call:
Directory.SetCurrentDirectory(GetBinFolder());
...
Of course, this problem could have been avoided if there was proper Inversion of Control in the code... don't have time to introduce it right now, but at least we removed some code duplication by creating a single GetBinFolder() method.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.