var blog = new ThoughtStream(me); RSS 2.0
 Wednesday, March 12, 2008

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.

Wednesday, March 12, 2008 7:18:32 AM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET | ASP.NET | Refactoring | WinForms

Navigation
About Me
View Derick Bailey's profile on LinkedIn

Send mail to the author(s) Contact Me
Archive
<December 2008>
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Derick Bailey
Sign In
Statistics
Total Posts: 91
This Year: 91
This Month: 0
This Week: 0
Comments: 40
Themes
Pick a theme:
All Content © 2008, Derick Bailey
DasBlog theme 'Business' created by Christoph De Baene (delarou)