Pages

Thursday, August 9, 2012

Combining file paths

When I develop something where file paths or file names must be combined, I’m always in doubt how to make sure backslashes are in the right place.

The simple example is when you need to combine a file path with a filename. Should the path end with a backslash or not? Did the user enter the path with an ending backslash or not in e.g. the parameters for the job?

You end up either ignoring one scenario or adding code to figure both out. This could eventual be a method where you decide it always returns the path with the ending backslash.

Well, in .NET there’s a static method, System.IO.Path.Combine, taking care of all this. You just pass it a number of paths and it ensures that backslashes are in the proper places in the returned string.

Here's a small example in X++:
static void PathCombine(Args _args)
{
    str         path1 = @"C:\TestDir";
    str         path2 = @"C:\TestDir\";
    str         path3 = "MyFolder";
    str         combination;

    combination = System.IO.Path::Combine(path1, path3);

    info (strFmt("Combinig '%1' with '%2' gives '%3'", path1, path3, combination));
    
    combination = System.IO.Path::Combine(path2, path3);

    info (strFmt("Combinig '%1' with '%2' gives '%3'", path2, path3, combination));
}