Thursday, January 31, 2008

[.NET] How to Retrieve Application Path - quick reference

Problem: You need to retrieve the application path but You don't remember (or you never knew) how to do it.

Solution: there are at least 3 well-known ways of ways to do this in .NET, let's see them in detail:

(1) the System.IO.Path way - more code but you always get what you're looking for; let's look at simple sample:

You start by using System.Reflection to get the application path comprehensive of the file name, either this way:

string pathWithFileName;

Or this Way:

pathWithFileName=System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.Replace("file:/", "");

Then you pass the pathWithFileName string to System.IO.Path.GetDirectoryName:

string pathWithoutFileName;
pathWithoutFileName = System.IO.Path.GetDirectoryName(code_Base);

(2) the Sytem.IO.Directory way - it's easier to type (since you'll be copy-pasting like a good butcher I don't see the catch) and to get but there is a severe drawback:


What's the severe drawback? Well if you previously changed the Current Directory using the SetCurrentDirectoy method you'll be getting that result instead of the the directory from where your assembly is being executed. If you're the only one working on your app, maybe that's ok, but if we're talking about huge banks of code... up to you, butcher.

(3) the System.Windows.Forms.Application way - if you're using windows forms you can use the StartupPath property:


Enough - have a good butcherin' day; You bet I will.

No comments: