Path.combine to combine two paths and backslash in second parameter

Hi,

system.IO.Path comes with many good function to work with the File system. some of them are ChangeExtension, GetDirectoryName, GetExtension, GetFileNameWithoutExtension, IsPathRooted etc.

The system.IO.Path.Combine is also include as a function in system.IO.Path to combine two paths provided to it. A few days back I was working with it to add paths provided by user. But I started getting erros where by sometimes the path would not be combined and only the second provided path was returned. After doing some research on this I got to the root of the cause.

The problem was only occuring when the second path provided in the method was starting with "\".

To make my understanding more accurate I made a small console applictaion to show what would be the result in differenct scenarios. Below are the situation and the output I got for them.

Console.WriteLine(System.IO.Path.Combine(@"D:\V\", @"S\test1.doc"));
Console Output - D:\V\S\test1.doc

Console.WriteLine(System.IO.Path.Combine(@"D:\V\", @"\S\test1.doc"));
Console Output - \S\test1.doc

Console.WriteLine(System.IO.Path.Combine(@"D:\V", @"S\test1.doc"));
Console Output - D:\V\S\test1.doc

Console.WriteLine(System.IO.Path.Combine(@"D:\V", @"\S\test1.doc"));
Console Output - \S\test1.doc

As we can see from the above results whenever the second path starts with "\" the result only includes the first path.

Hence we should be cautions when we are using the Path.Combine function to combine two function.

Vikram


Share this post   Email it

Feedback

Posted on 7/24/2009 3:09:50 AM

Hi Vikram, I regularly watch ur blog. I have a doubt. Here in ur post "Setting and retrieving default printer from code" ... I imported the namespace, and [DllImport("winspool.drv", SetLastError = true)]
but when I type System. "Drawing" namespace is not getting. How can I get it...?

Posted on 7/24/2009 8:44:20 AM

HI Pawan,
The System.Drawing Namespace is in the System.Drawing Assembly which does not get referenced by default. You need to add the reference to the dll in the project.

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2010 Vikram Lakhotia