Path Combine: Leading Slash in relative path

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.

Anonymous's picture

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

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <p> <span> <div> <h1> <h2> <h3> <h4> <h5> <h6> <img> <map> <area> <hr><br> <br /> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <em> <b> <u> <i> <strong><font> <del> <ins> <sub> <sup> <quote> <blockquote> <pre> <address> <code> <cite> <embed> <object> <param> <strike> <caption>
  • You can enable syntax highlighting of source code with the following tags: <c>, <cpp>, <csharp>, <drupal5>, <drupal6>, <java>, <javascript>, <mysql>, <php>, <python>, <ruby>, <sql>, <tsql>, <vbnet>, <xml>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Lines and paragraphs break automatically.

More information about formatting options

Who's online

There are currently 0 users and 6 guests online.

Recent Answers

Anonymous added a answer to 301 Redirect in (1 day 16 hours ago)
Anonymous added a answer to LC3 Assembly Palindrome Program (3 years 28 weeks ago)
Anonymous added a answer to LC3 Assembly Palindrome Program (3 years 28 weeks ago)
Anonymous added a answer to Error-GetTypeHashCode()': no suitable method found to override (3 years 45 weeks ago)
Anonymous added a answer to AutoIncrement vs UniqueIdentifier (4 years 18 weeks ago)
vaibhav added a answer to Linq query on Datatable (4 years 19 weeks ago)