Path Combine: Leading Slash in relative path
Submitted by vaibhav on Thu, 05/26/2011 - 15:14
System.IO.Path.Combine is one of the scarcely used method provided by .Net Framework. It is used to combine two strings in to a complete path. Path.Combine is also essential for cross-platform coding as it uses whatever path separator the current OS uses.
string basePath = @"c:\"; string relativePath1 = "MyDocuments"; string relativePath2 = "hello.txt"; string combinedPath1 = basePath + relativePath1 + "\\" + relativePath2; //Traditional Way string combinedPath2 = System.IO.Path.Combine(basePath, relativePath1, relativePath2); string combinedPath3 = System.IO.Path.Combine(basePath,"\\", relativePath1, relativePath2);
But take care of leading slash in relative path, if you add a leading slash in relative path Path.Combine will drop the basePath. You can add a trailing slash in first parameter i.e. string basePath = @"c:\";
Output of the above statements is
combinedPath1 : c:\MyDocuments\hello.txt;
combinedPath2 : c:\MyDocuments\hello.txt;
combinedPath3 : \MyDocuments\hello.txt; //first parameter i.e basePath has been dropped.
Good post
What a wonderful guide for me? For a longtime, I have been searched for this but now only I got your blog through Google. Thanks for sharing. Keep on posting...
Post new comment