Geeks With Blogs
Phubar Baz Musings of an HTML5 Programmer

Here's a little used gem in .Net. In the Path class there is a Combine method. What this method does is to properly combine two parts of a file path. For example, you may have a path that you want to write a file to and a name of the file to write. I've seen a lot of code where in this case most programmers just string concat the path and file name. This doesn't always work right if you don't think about it.

That's where Path.Combine comes in. You don't have to think about the details of combining a file to a path. It does it properly for you. I ran into some code the other day where it was concatenating a path to a temporary directory with a file name to create a temporary file. The problem was that when called from one place it was tacking a backslash onto the end of the path. And from another place it wasn't. So in the second case the last part of the path was becoming part of the filename. This caused the temp file to be placed in the wrong directory.

path = "c:\somefolder\temp";

filename = "tempfile.txt";

filepath = path + filename;

Then filename ends up being: "c:\somefolder\temptempfile.txt".

If they would have used Path.Combine instead it would have created the proper path in either case: "c:\somefolder\temp\tempfile.txt". There's no need to worry about adding a slash at the end of the path or not.

Posted on Friday, August 12, 2011 10:16 AM | Back to top


Comments on this post: Path.Combine

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © PhubarBaz | Powered by: GeeksWithBlogs.net