Get Filenames from Directory using SAS Macro

The following SAS macro will get the listing of file and directory names in the specified input directory name and place them into the work.files dataset. The macro works with the paths with special characters (see example usage below).


%macro getFiles(inDirectory);

filename _dir_ "%bquote (&inDirectory.)";

data files (keep = filename);
handle = dopen ( '_dir_' );
if handle > 0 then do;
count = dnum (handle);
do i = 1 to count;
filename = dread (handle, i);
output files;
end;
end;
rc = dclose (handle);
run;

filename _dir_ clear;

%mend;

* %getFiles - populates work.files dataset with the listing of file names in the directory
* specified as a parameter. ;
%getFiles(c:\New Folder);
*%getFilenames(%bquote(c:\Documents and Settings\'directory'));