Search This Blog

Loading...

Tuesday, May 20, 2008

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?

5 comments:

pcsolotto said...

Whoever owns this blog, I would like to say that he has a great idea of choosing a topic.

Niki said...

How about Process.GetCurrentProcess().MainModule.FileName, shouldn't that work in any case? I haven't tried in with a shadow copy, though.

Soon Hui said...

Hi niki, thanks for the input.

As far as I know, Process.GetCurrentProcess().MainModule.FileName
doesn't work because it returns the path of the executable that invokes the assembly. If you attach your debugging to NUnit, then it will return the location of NUnit.exe. But what we want is the location of the assembly you test under NUnit, not NUnit.exe itself.

Hope this clarifies things a little.

romank said...

I usually use
new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath

ruNury said...

Assebly.GetExecutionAssembly().Location

if u want the diretory without the exe-file, that is!