X

C# tip: Use Path Combine for file or directory path information

dotnet C#

.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

string path = somePath + "\\" + filename;

But by using Path.Combine we can provide a cross platform path

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.

Categories: .NET C#
Taswar Bhatti:

View Comments (1)

  • 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".

Related Post