Building a File Path with Path.Combine
When using a variety of input methods to accept a file path and file name, the format of the results can vary. To avoid the problems of checking for path separator characters and adding or removing them as required, .NET provides a method to provide this.
The System.IO namespace contains classes that provide input and output functionality for streams, files and folders. Within this namespace is the Path class, which performs operations on strings that contain file path information. One of the class's methods, named Combine, can be used to concatenate path fragments whilst automatically handling the problems of missing separator characters.
The Combine method accepts two string parameters. Each is a fragment of a file path to be combined. The method appends the second parameter to the first and returns the new path according to the following rules.
- If the first path is a drive letter only, eg. "C:", it remains unchanged.
- If the first path is not just a drive letter, the combine method ensures that it ends with a separator character.
- If the second parameter starts with a separator character it is assumed to be a root folder and is returned as the result of the entire operation.
- If the second parameter does not start with a separator character it is appended to the first parameter.
The examples below demonstrate the four rules. Ensure that you have added using System.IO; to the start of your code file to execute the following:
4 November 2007