Directory Listing using Coldfusion 8 and .NET
Tagged Under : ColdFusion
After doing my first example with CF8 and .NET, I got a little excited and wanted to do more with it. I am not really a .NET guy and have very little know-how of how it works. However, I have been trying to do something rather useful with it and I thought it might be a good idea to actually try to mimick the CFDirectory functionality using .NET objects. I have done that previously in Java as well but this time around its .NET .
For those, who are not aware, the mscorlib assembly is always included by default whenever .NET objects are created using Coldfusion. Therefore, we dont need to specify explicitly the “Assembly” attribute in the CFOBJECT or CreateObject call. Because my example uses System.IO.DirectoryInfo which is a part of mscorlib, so I dont need to specify an assembly here.
I will post the UDF here, but would like to highlight parts of it before I do that.
What the above code does is, it tries to connect to an already existing Object of DirectoryInfo and SearchOption and if it fails, it creates a new Object. This is require in order to avoid multiple creations of the same Object. SearchOption object will let us apply the “recurse” functionality to our UDF. It has 2 properties, TopDirectoryOnly and AllDirectories, and based on what we tell it to do, it returns the files accordingly.
Next, based on the argument, to list dir or files, we call either the GetFiles() method or the GetDirectories() method. It really is a matter of browsing the System.IO.DirectoryInfo assembly and looking at the available methods and their returntypes and expected parameters. I wont go into all those details here as that would make the post very long but in my previous post, I did talk about how to browse a .NET assembly.
So, here is the UDF that I wrote, it takes 4 arguments.
Directory - the initial directory to start with
filter - the type of Filter to specify, e.g. *.jpg
recurse - true or false
type - dir or file
And here is an example of how to use it.
I havent seen a lot of Coldfusion8 and .NET examples out there and given the fact that I am a novice at .NET, this code might not be the best code, but if anyone has suggestions, please give me a shout.