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));


Daniel Grau said...

hi Palle,
this function has been in Axapta for quite a while :)

Skaue said...

I reckon you still need to assert CLR Interop if the code needs to run server side. :-)

new InteropPermission(InteropKind::ClrInterop).assert();

Palle Agermark said...

True - you'd need the InteropPermission.

I considered adding it, but decided to make the example as simple as possible.

And now you have added it :-)

Palle Agermark said...

Daniel thanks for the tip.

The only thing about that method is that I still need to deal with the backslash. By calling it, I'll of course know that it'll be in the returned string.

With System.IO.Path.Combine I don't have to check the path first and the add the file name.
It feels like a slightly less hassle, with one operation less :-)

And System.IO.Path.Combine has some other interesting overloads.

Daniel Grau said...

yes, there are some nice other methods indeed!

I always stick my filenames together with ...strFmt("%1%2",Docu::fileCheckPath(yourPath), yourFileName)... with this you don't have to care about the backslash either :). and as Skaue mentioned, you don't have to care about InteropPermission like this.

but either way, it's much easier than checking manually if there's a backslash at the end..

SBE said...

Hello ,
what is the correct form of a file path if we want to delete it by using the method System.IO.File::Delete().

Palle Agermark said...

Check this dokumention: