27 lines
1.4 KiB
C#
27 lines
1.4 KiB
C#
using System.IO;
|
|
|
|
namespace WebDesktopBackend.Extentions {
|
|
public static class DirectoryInfoExtentions {
|
|
/// <summary>
|
|
/// Returns the size of the Directory (from: https://stackoverflow.com/a/32364847)
|
|
/// </summary>
|
|
/// <param name="directoryInfo">The Directory</param>
|
|
/// <param name="recursive">When set to true, the Functions includes also Subdirectories</param>
|
|
/// <returns>The size of the Directory</returns>
|
|
public static long GetDirectorySize(this DirectoryInfo directoryInfo, bool recursive = true) {
|
|
var startDirectorySize = default(long);
|
|
if (directoryInfo == null || !directoryInfo.Exists)
|
|
return startDirectorySize; //Return 0 while Directory does not exist.
|
|
|
|
//Add size of files in the Current Directory to main size.
|
|
foreach (var fileInfo in directoryInfo.GetFiles())
|
|
System.Threading.Interlocked.Add(ref startDirectorySize, fileInfo.Length);
|
|
|
|
if (recursive) //Loop on Sub Direcotries in the Current Directory and Calculate it's files size.
|
|
System.Threading.Tasks.Parallel.ForEach(directoryInfo.GetDirectories(), (subDirectory) =>
|
|
System.Threading.Interlocked.Add(ref startDirectorySize, GetDirectorySize(subDirectory, recursive)));
|
|
|
|
return startDirectorySize; //Return full Size of this Directory.
|
|
}
|
|
}
|
|
} |