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
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);
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