Search code examples
windows-7sasenterprise-guide

How can I check if a directory already exists and if not, create it?


How can I check if a directory already exists and if not, create it?

I am using a SAS 9.3 server with SAS EG 5.1 under Windows 7.

%macro chk_dir(dir=) ; 
   options noxwait; 
   %local rc fileref ; 
   %let rc = %sysfunc(filename(fileref,&dir)) ; 
   %if %sysfunc(fexist(&fileref))  %then 
      %put NOTE: The directory "&dir" exists ; 
   %else 
     %do ; 
         %sysexec md   &dir ; 
         %put %sysfunc(sysmsg()) The directory has been created. ; 
   %end ; 
   %let rc=%sysfunc(filename(fileref)) ; 
%mend chk_dir ; 

This code comes from the SAS website.

However when I try to create a folder using this macro, %chk_dir(dir=E:\foo\20140904_test);, it fails to create the folder and I get the following log message:

MLOGIC(CHK_DIR):  %SYSEXEC  md   &dir
SYMBOLGEN:  Macro variable DIR resolves to E:\foo\20140904_test
ERROR: Shell escape is not valid in this SAS session. 
MLOGIC(CHK_DIR):  %PUT %sysfunc(sysmsg()) The directory has been created.

The directory E:\foo' does exist and calling %chk_dir(dir=E:\foo); gives log output : NOTE: The directory "E:\foo" exists as expected.


Solution

  • you may add

    Options DLCREATEDIR;
    

    to your code - this will automatically create folder if it not exists. Otherwise you will receive an error if you try to save results to folder that do not exist.

    But this only solves saving, it doen't offer any solution if you just want to check.