.NET provides in its System.IO namespace the Path class which performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.
Most of the time we see develeopers writing code like
1 |
string path = somePath + "\\" + filename; |
But by using Path.Combine we can provide a cross platform path
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
string somePath = @"C:\temp"; string filename = "dat.txt"; string path = Path.Combine(somePath,filename); //produce an output of C:\temp\dat.txt //linux: C:/temp/dat.txt string[] paths = {@"c:\My Music", "2013", "media", "banner"}; string fullPath = Path.Combine(paths); //output c:\My Music\2013\media\banner string path1 = @"C:\Temp"; string path2 = "My Music"; fullPath = Path.Combine(path1, path2); //output: C:\Temp\My Music fullPath = Path.Combine(string.Empty, path2); //output: My Music fullPath = Path.Combine(path1, string.Empty); //output: C:\Temp |
By using the Path and Combine method, one can at least eliminate some of the headache of porting to another platform.
string myString = System.IO.Path.GetFullPath( Path.Combine( @”C:\aa” , @”..\aa\bbb\”) );
// Fuller Answer: myString == @”C:\aa\bbb\” .
// The final trailing backslash (\) would NOT be in the answer IF the parameter value into .Combine had instead been @”..\aa\bbb”.