Published articles on other web sites*

Published articles on other web sites*

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:
This code is buggy! You may not realize it at the first glance, but the output produced is
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
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);
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
I would love to see this API enhanced in .NET 5 to allow for Absolute path conversion and path validity check.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...