Path.Combine saves the day…again

I”ve already blogged about the cool utility Path class. However, it seems like there still are some people that prefer to do it the hardway :,,)

Here”s an example of a question I”ve received: “How can I return the full path to a file? I mean, I might receive a local path…in that case, I need to set the full path to the current directory + filename (ie, where the assembly is running). If I receive the full path for that filename, then I just need to return that path…”

This is where Path.Combine really shines. Don”t believe me? Then look at the following code:

String path = Assembly.GetExecutingAssembly().Location; //get full path to the executing assembly
Console.WriteLine(Path.Combine(
                                  Path.GetDirectoryName(path),
                                  filename)
                            );

That should really do it (ok, there are some variations on this…you could go grazy and create a Uri and then go for its local path property, but this works for the current problem I was describing)! No need to do the parsing if someone has already written (and, more important, tested!) the code that does what you want, don”t you think?

Advertisements

~ by Luis Abreu on May 6, 2008.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: