Use ColdFusion to Find Out What Directory or Folder You're In

Have you ever wanted to find out what folder or directory a particular page or template resides in, but NOT necessarily the entire path to the page? Well, Raymond Camden recently blogged about it, so I know of at least one other developer (including myself) who has asked that question so I thought it would be worthy of mention here.

Ray mentions a number of extremely useful functions and the person who submitted the question was actually quite close to answering their own question (just as I too find myself on so many occaisions).

Let's say you have a file "index.cfm" which resides at "www.example.com/folder/" which as it might turn out translates to "D:\inetpub\example\folder\". Maybe you just want to return "folder" but don't need anything else. Let's try a couple of different options to see what happens.


<cfset thisPath = ExpandPath("*.*") />
<cfoutput>#getDirectoryFromPath(thisPath)#</cfoutput>

This produces "D:\inetpub\example\folder\"

Well, that's not what we wanted is it? Let's try another way.


<cfset thisDirectory = ExpandPath(".") />
<cfoutput>#getDirectoryFromPath(thisDirectory)#</cfoutput>

This produces "D:\inetpub\example\"

Hmm, while this isn't what we wanted, it is kind of interesting. But we're not quite there, so lets try another method.


<cfset thisDirectory = ExpandPath(".") />
<cfoutput>#getFileFromPath(thisDirectory)#</cfoutput>

Aha! This produces "folder" just like we wanted!

Does this help you? Let me know.

Comments

I thought I should also mention a couple of other methods too:

1) Using some of the same tags listed in my article you could also get at the current folder using this:

<cfoutput>
#listlast(GetDirectoryFromPath(GetCurrentTemplatePath()), "\")#
</cfoutput>

Or, better yet, ever need to know the drive letter of your web site? Try this:

<cfoutput>
#listfirst(GetDirectoryFromPath(GetCurrentTemplatePath()), "\")#
</cfoutput>

2) Dan G. Switzer, II created a nifty UDF which would work when using virtual directories: (http://blog.pengoworks.com/index.cfm/2008/5/8/Gett...)

3) And one more example:

<cfoutput>
#listlast(GetDirectoryFromPath(cgi.script_name), '/')#
</cfoutput>
# Posted By Stephen Withington | 5/12/08 12:56 PM

© 2026, Stephen J. Withington, Jr.  |  Hosted by Hostek.com

Creative Commons License   |   This work is licensed under a Creative Commons Attribution 3.0 Unported License.