Put Your Path Together with Path.Combine
At least in my history of programming I have always concatenated paths as I build them in my code. A good example of this is deciding where to store uploaded photos in a photo album. There are really two paths that need to be managed, the physical path on the server and the direct URL to the photo. It always seemed to break at one point or another with my sites, typically at some random time when I was extremely busy with another project and working against a deadline.
I think I remember seeing the Path.Combine function a few years ago, but what it does did not register in my normal coding mind set. As I wrote my book last year I kept seeing it used in the framework code as I analyzed it in Reflector. So I started investigating just how I could use it and now make it a routine GoTo method.
The Combine method is a static or shared function that returns a full path, properly combining the two strings passed into a valid path. The really nice thing is that it will do the work for us to create valid physical, shared or URL paths. This is very important because now I really do not need to manage several methods in my head to take care of each scenario, making my life much easier.
Since starting to use the path.combined method I have found that my code is much more consistent and I have fewer errors when it comes to working with file paths. One neat trick I have figured out is that I can combine directory structures and then combine the file name at the end of the string. On a related topic I have also discovered that I can use the file not exist method to verify that the actual file exist, again making my code more robust and error free. Another important property that I have begun using is the Request.PhysicalAppliccationPath property, because it returns that actual physical path to the site is stored on the server.
An Example using Path.Combine from my upcoming httpHandler WROX BLOX
'First run the supplied filename through a URL decoder to change any URL
'characters back to their normal selves.
sDocument = HttpUtility.UrlDecode( _
'Now build a full physical path to the file on the server.
sDocument = Path.Combine(Path.Combine( _
context.Request.PhysicalApplicationPath, "PDF"), sDocument)