Skip to content
⌘ NSIS Forum Archive

Get the count of total number of files under a folder.

8 posts

reachb4#

Get the count of total number of files under a folder.

Hi,

What is the script to get the count of files under a folder?


Please advice.


Thanks in advance,

Regards,
John.
Highcoder#
:-)

As a famous philosoph said a long time ago: "RTFM!" 😁
Joke...

But exactly there is the answer. Keyword: "File Functions Header"

!include "FileFunc.nsh"

Section "GetFileCount"
${GetSize} "C:\YourFolder" "/G=0" $0 $1 $2 ;file count in YourFolder or...
${GetSize} "C:\YourFolder" "/G=1" $0 $1 $2 ;file count in YourFolder include Subdirectorys!
; $0 = contains the size normaly but the option S=nothing means "don´t get size, faster"
; $1 = filecount
; $2 = directorycount
SectionEnd
have fun

cheers
pengyou#
The NSIS User Manual has some appendices describing lots of useful functions together with sample code showing how to use them.

Appendix E.1 (File Functions Header) includes the GetSize function which can be used to count the number of files in a folder or in a folder and its sub-folders:
MSG#
Or if you don't need recursive searches, you can just use something simple like this:

StrCpy $dirs 0
StrCpy $files 0
FindFirst $0 $1 "C:\YourPath\*.*"
loop:
  StrCmp $1 "" done
  ${If} ${FileExists} "$1\*.*"
    IntOp $dirs $dirs + 1
  ${Else}
    IntOp $files $files + 1
  ${EndIf}
  FindNext $0 $1
  Goto loop
done:
FindClose $0 
The manual is your friend. http://nsis.sourceforge.net/Docs/Chapter4.html
Afrow UK#
You need to ignore $1 if it is . or ..:
ClearErrors
FindFirst $0 $1 "C:\YourPath\*.*"
${DoUntil} ${Errors}
${If} $1 != .
${AndIf} $1 != ..
${If} ${FileExists} "C:\YourPath\$1\*.*"
IntOp $dirs $dirs + 1
${Else}
IntOp $files $files + 1
${EndIf}
${EndIf}
FindNext $0 $1
${Loop}
FindClose $0
Stu
MSG#
Originally Posted by Afrow UK View Post
You need to ignore $1 if it is .. otherwise it will count the files and folders in the parent folder as well!
I don't see how it would count the files from parent. It would simply add two counts to $dirs. FindFirst/Next isn't recursive, either down or up the tree. You can solve the two extra counts by using StrCpy $dirs -2 at the beginning, instead of 0. Saves a bunch of Ifs (but probably breaks if the search directory doesn't exist).
Afrow UK#
Sorry you are right of course. Fixed the error with the FileExist check ($1 is only the file name, not the complete path).

Stu