You are hereBlogs / Aakash's blog / Path Combine: Leading Slash in relative path

Path Combine: Leading Slash in relative path


By Aakash - Posted on 26 May 2011

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.

 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