· Nov 22, 2021

How to lists all files in a given folder (and sub-folders if needed)

Hi Community,

I recently needed to interrogate some folders/sub-folders to retrieve filenames using cache object script(COS) and I implemented it in the following way.

ClassMethod ListDir(
               path = "",
               wildchar = "*",
               recursive As %String(VALUELIST=",y,n") = "y",
               ByRef dirlist)
               i path'=""{
                              i ##class(%File).DirectoryExists(path){
                                             s rs=##class(%ResultSet).%New("%File:FileSet")
                                             s sc=rs.Execute(path,wildchar,"",1)
                                                            s name=rs.Data("Name")
                                                            s type=rs.Data("Type")
                                                            // if sub-folder loop once more
                                                            i type="D",recursive="y"{
                                                                           d ..ListDir(name,wildchar,"y",.dirlist)
                                                            // if file add to list
                                                            i type="F"{
                                                                           s dirlist($i(dirlist))=name
                                             d rs.Close()

The code passes the output as an array (dirlist). Setting the recursive flag to "y" will loop through individual sub-folders and providing a value for wild-char will restrict the result to your desired extension. Pretty sure there's probably a better way to do this, but this worked for me and results are returned fairly quickly. I hope you find it useful.

Product version: Caché 2018.1
$ZV: Cache for Windows (x86-64) 2018.1.1 (Build 312U)
Discussion (8)1
Log in or sign up to continue

This (getFiles) method is marked as internal in Cache, and yes, it's typical internal as it's usage is relied on the strong internals knowledge :). Besides, it's hidden in IRIS, and its caller should be rewritten to achieve DBMS independence:

 ClassMethod ListDir2(path = "", wildchar = "*", recursive As %String(VALUELIST=",y,n") = "y", ByRef dirlist)

#if $zversion["IRIS"
 @temp@(pTempNode)  ;zw dirlist