Check if dir is empty

From NSIS Wiki
Jump to navigationJump to search
Author: camillo (talk, contrib)


Description

Because "ifFileExists" uses the format "ifFileExists 'Directory\*.*'" to determine whether the -directory- exists or not, you can't use it to check whether the directory is empty or not.
Here is a simple but useful function to check whether a directory is empty. Based largely on http://nsis.sourceforge.net/Delete_dir_only_if_empty .

How To Use

Push <directory>
Call isEmptyDir
Pop <result>

Example

Push "c:\somedir\"
Call isEmptyDir
Pop $0
StrCmp $0 1 0 +2
  MessageBox MB_OK "Directory is empty"
StrCmp $0 0 0 +2
  MessageBox MB_OK "Directory is NOT empty"

The Function

Function isEmptyDir
  # Stack ->                    # Stack: <directory>
  Exch $0                       # Stack: $0
  Push $1                       # Stack: $1, $0
  FindFirst $0 $1 "$0\*.*"
  strcmp $1 "." 0 _notempty
    FindNext $0 $1
    strcmp $1 ".." 0 _notempty
      ClearErrors
      FindNext $0 $1
      IfErrors 0 _notempty
        FindClose $0
        Pop $1                  # Stack: $0
        StrCpy $0 1
        Exch $0                 # Stack: 1 (true)
        goto _end
     _notempty:
       FindClose $0
       ClearErrors
       Pop $1                   # Stack: $0
       StrCpy $0 0
       Exch $0                  # Stack: 0 (false)
  _end:
FunctionEnd