Use Path.Combine instead of Concatenating Paths

I always advice developers to use System.IO.Path.Combine instead of doing string path concatenation. Here’s why! While concatenating paths in your .NET applications, I often come across the following code:

pathconcat

This code is buggy! You may not realize it at the first glance, but the output produced is

C:\MyFilessomefile.txt

The folderPath does not end with a valid separator character i.e a trailing slash is missing after ‘\’. Now if you write the following code using Path.Combine, the output is as follows:

// code from DevCurry.com
string folderPath = "C:\\MyFiles";
string filePath = "somefile.txt";

string entirePath = folderPath + filePath;
Console.WriteLine("Using String Concat :\n" + entirePath);

entirePath = Path.Combine(folderPath, filePath);
Console.WriteLine("\nUsing Path.Combine :\n" + entirePath);

image

As you can see, a separator is appended to folderPath before concatenation. So get into the habit of using Path.Combine in your application and it will save you a lot of time during application maintenance.

There are many more similar checks that are taken care of if you are using Path.Combine. It has 4 overloads that you can check here

image

I would love to see this API enhanced in .NET 5 to allow for Absolute path conversion and path validity check.

Check some more useful .NET Tips






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Toni said...

You can use Path.GetFullPath to convert relative path to absolute. Path validation is a bit tricky unless it assumes that all the parts must exist. There are some open source projects such as:
http://filedirectorypath.codeplex.com/
http://fluentpath.codeplex.com/