Jan 23

Are you working with paths?

Posted in C# Trivia      Comments Off on Are you working with paths?

I believe that everyone has had to (at least once) write code that needs to work with paths. How many of us have gone into writing something like this:

String basePath = “c:\myPath”;
String fileName  = “myfile.doc”;
String completeFilePath = basePath + “\” + “myfile.doc”;

That was the best possible scenario. How many times did you had to write code to check if the basePath ended with the necessary char before adding one? Have you been there? (I believe that everyone has done written code like this at least once!) Are you still doing that? NO. Ok. You can stop reading :,,)

If you”re still reading, then you still haven”t heard of the Path and VirtualPathUtility utility classes. Whenever you need to work with paths, do use these classes. Both of them have several cool methods which will help you getting your paths right. For instance, getting the complete path in the previous example could be done like this:

String basePath = “c:\myPath”;
String fileName  = “myfile.doc”;
String completeFilePath = Path.Combine(basePath, filename);

You may be wondering why I have decided to write about this topic. Well, You might not believe me, but there are still lots of guys out there that haven”t heard about these classes. Even worst, I”ve just finished reading an article which works with paths and uses the string concatenation approach for getting a file name…