Easy cross platform and environment file paths

One of the very useful and underrated functions in ColdFusion is the humble ExpandPath function. It has saved my life on many occasion and I just thought I'd explain how it works and what it does.

If you or dealing with file or directory manipulation on from CF then you will often need a way to get a file system path. You could just use it as follows:

<cfdirectory action="list" name="dirList" directory="c:\farcry\myApp">

This is of course very nasty as when you put this onto your live server you may not have farcry installed in c:\ - it may be somewhere completely different (particularly on shared hosting). Alternatively your live server may be a linux box in which case there is no "C:" drive at all.

To solve this and make you applications nice an portable you can use expandPath on a cf mapping. So assuming you have a cf mapping for /farcry to c:/farcry you would use the following:

<cfdirectory action="list" name="dirList" directory="#expandPath('/farcry')#/myApp">

This will now happily run on any machine that has the farcry mapping and will map to whatever location the mapping points to.

Cheers, Mark

Comments
Comments are not allowed for this entry.
BlogCFC was created by Raymond Camden. This blog is running version 5.1.004.