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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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/