Created
March 18, 2021 00:38
-
-
Save Benshi/af8d0bb4bc1ae28768567f72f0b87120 to your computer and use it in GitHub Desktop.
DirectoryInfoExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// >= .NET 5.0 | |
using System; | |
using System.IO; | |
using System.Threading; | |
using System.Threading.Tasks; | |
public static class DirectoryInfoExtensions | |
{ | |
/// <summary> | |
/// ディレクトリのサイズを返します。 | |
/// </summary> | |
public static long GetDirectorySize(this DirectoryInfo directoryInfo) | |
{ | |
long startDirectorySize = 0L; | |
if (directoryInfo == null || !directoryInfo.Exists) | |
{ | |
return startDirectorySize; | |
} | |
var eo = new EnumerationOptions | |
{ | |
AttributesToSkip = FileAttributes.ReparsePoint | FileAttributes.Offline | FileAttributes.Device, | |
ReturnSpecialDirectories = false, | |
RecurseSubdirectories = false, | |
}; | |
foreach (var fileInfo in directoryInfo.EnumerateFiles("*", eo)) | |
{ | |
Interlocked.Add(ref startDirectorySize, fileInfo.Length); | |
} | |
Parallel.ForEach(directoryInfo.EnumerateDirectories("*", eo), | |
subDirectory => Interlocked.Add(ref startDirectorySize, GetDirectorySize(subDirectory))); | |
return startDirectorySize; | |
} | |
} | |
/* | |
class Program | |
{ | |
static void Main() | |
{ | |
var di = new System.IO.DirectoryInfo(@"C:\Program Files"); | |
Console.WriteLine(di.FullName); | |
Console.WriteLine($"{di.GetDirectorySize():N0} Bytes"); | |
Console.ReadLine(); | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment