# how to get the size of a directory(total size of all files under this directory or its subdir or …)

I use Mathematica10 in my Win7 and I want to estimate the amount of disk space occupied by each dirs.

I try the code(the code was copied from How do I find the amount of free space on disk?, actually I don't know how it works at all):

dirsofD = FileNames["*", "D:\\"]


and

sizeoddirsofD =
ToExpression@
StringJoin[
ReadList["!dir " <> #, Word, RecordLists -> True,
WordSeparators -> {" ", ","}][[-2, 3 ;; -2]]] & /@ dirsofD


However, the code above only count the files directive under certain dir while the files under subdirs of given dir are missed, which means the search depth is only one. How could I get the whole size of all files of certain dir?

• If you are okay with using another program, WinDirStat has got to be one of the coolest little freeware programs to do this. – Jason B. Dec 3 '15 at 9:27

There is also a function in the Internal context (for now) that does that
InternalDirectoryByteCount[$InstallationDirectory] (* 6794576686 *)  which is in agreement with what my OS reports for that directory An estimate can be obtained without resorting to the underlying OS. FileByteCount can be used to obtain the size of a file and FileNames can list files to any depth so combining these in to a function: recursiveFolderSize[folder_String] := Plus @@ Quiet[ FileByteCount /@ FileNames["*", folder, Infinity] /.$Failed -> 0,

FileByteCount gives a message and returns \$Failed for directories so the function handles these cases.