Path.Combine - Be aware of a Slash in the Second Parameter
Hilton Giesenow's Jumbled Mind - Incorrect Results With Path.Combine
"...
There are a few interesting combinations of what will and won't combine correctly, and the MSDN page for Path.Combine explains some of these. There's one condition it won't cater for properly though - if the 2nd parameter contains a leading '\', for instance '\myfile.txt', the final result will ignore the first parameter. The output of Path.Combine("c:\temp", "\myfile.txt") is \myfile.txt'. This is not the case if the 1st parameter contains a trailing '\'. See the following for more info:
string part1 = @"c:\temp";
string part2 = @"assembly1.dll";
(1) Console.WriteLine(Path.Combine(part1, part2));
(2) Console.WriteLine(Path.Combine(part1 + @"\", part2));
(3) Console.WriteLine(Path.Combine(part1 + @"\", @"\" + part2));
(4) Console.WriteLine(Path.Combine(part1, @"\" + part2));(1) c:\temp\assembly1.dll
(2) c:\temp\assembly1.dll
(3) \assembly1.dll
(4) \assembly1.dllSo the moral is - check your 2nd path for a leading '\'." [90% Post Leach]
You learn something every day...
I use Path.Combine all the time and this taught me something new. I kind of thought/assumed it would handle this for me (i.e. Not result in #3 & #4 but combine the paths like #1 & #2).
It makes sense in hindsight though, as "\file.ext" means "root\file.ext", still this is a behavior to be aware of if you're using Path.Combine...
1 comment:
Thanx for the info, saved me a lot of time wondering why it doesnt work.
Post a Comment