Search This Blog

Loading...

Tuesday, May 20, 2008

Ask Google: What is a Responsible Crash

Speaking of crashing responsibly, I am not sure whether this is a responsible crash?

How to Get the File Path of an Executing Assembly?

Getting the directory, or the file path of an executing assembly can be very tricky. How did you do it?

You can try Application.ExecutablePath. But you need to make reference to System.Windows.Forms. This may not be a good idea if you want your class library to steer clear of forms and UI stuff.

You can try the Assembly.GetExecutingAssembly().Location. But if, somehow, you do a "Shadow Copy" before you run your application (like the default NUnit behavior), then this property will return you the shadow copy location, not the real, physical location.

The best way is to implement a function that calls the CodeBase property of Assembly object and chop off the irrelevant portion of the string. It's a shame that Microsoft doesn't provide a nice property to do this. So we need to code by hand. Here's the code:



public static string RealAssemblyFilePath()
{
string dllPath=Assembly.GetExecutingAssembly().CodeBase.Substring(8);
return dllPath;
}

Ugly! I know, but it works, and this is how I implement it in my unit testing project.

Anyone has a better idea?