Thursday, December 5, 2013

Let the API do the heavy lifting

Instead of concatenating directory and filename manually:

string dir = @"C:\Windows";
string filename = "notepad.exe";
Console.WriteLine(dir + @"\" + filename);


Use Path.Combine:

string dir = @"C:\Windows";
string filename = "notepad.exe";
Console.WriteLine(Path.Combine(dir, filename));


Output: C:\Windows\notepad.exe


Aside from it take care of the nuances of platform differences(slash for *nix-based systems (e.g. Mono on Linux), backslash for Windows-based), it also takes care of trailing slash/backslash of the directory


The output of the following is still: C:\Windows\notepad.exe

string dir = @"C:\Windows\";
string filename = "notepad.exe";
Console.WriteLine(Path.Combine(dir, filename));


C# on Unix: http://ideone.com/rTACSJ

C# on Windows: http://dotnetfiddle.net/kxVNW5



Happy Coding! ツ

No comments:

Post a Comment