How do I get a directory size (files in the directory) in C#?
.net, asp.net, c#, winforms
Solution
If you use `Directory.GetFiles` you can do a recursive seach (using `SearchOption.AllDirectories`), but this is a bit flaky anyway (especially if you don't have access to one of the sub-directories) - and might involve a huge single array coming back (warning klaxon...).
I'd be happy with the recursion approach unless I could show (via profiling) a bottleneck; and then I'd probably switch to (single-level) `Directory.GetFiles`, using a `Queue<string>` to emulate recursion.
Note that .NET 4.0 introduces some enumerator-based file/directory listing methods which save on the big arrays.
Problem
I want to be able to get the size of one of the local directories using C#. I'm trying to avoid the following (pseudo like code), although in the worst case scenario I will have to settle for this: ``` int GetSize(Directory) { int Size = 0; foreach ( File in Directory ) { FileInfo fInfo of File; Size += fInfo.Size; } foreach ( SubDirectory in Directory ) { Size += GetSize(SubDirectory); } return Size; } ``` Basically, is there a Walk() available somewhere so that I can walk through the directory tree? Which would save the recursion of going through each sub-directory.