Это может вас где-то получить
Дано
public static class MyExtension
{
static readonly string[] _sizeSuffixes ={ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
public static string ToSize(this long value, int decimalPlaces = 1)
{
if (value < 0) { return "-" + ToSize(-value); }
var i = 0;
var dValue = (decimal)value;
while (Math.Round(dValue, decimalPlaces) >= 1000)
{
dValue /= 1024;
i++;
}
return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, _sizeSuffixes[i]);
}
}
Класс
public class Info
{
public Info(DirectoryInfo directoryInfo)
{
DirectoryInfo = directoryInfo;
Name = directoryInfo.FullName;
}
public Info(FileInfo fileInfo)
{
Name = fileInfo.FullName;
Size = fileInfo.Length;
}
public DirectoryInfo DirectoryInfo { get; }
public string Name { get; set; }
public long Size { get; set; }
public List<Info> Children { get; set; } = new List<Info>();
public List<Info> GetDirectories()
{
if (DirectoryInfo == null) return Children;
var dirs = DirectoryInfo.EnumerateDirectories()
.Select(x => new Info(x))
.ToList();
Children = dirs;
Children.AddRange(DirectoryInfo.EnumerateFiles().Select(x => new Info(x)));
return dirs;
}
public void Order()
{
if (Children == null) return;
Children = Children.OrderBy(x => x.Children == null).ThenByDescending(x => x.Size).ToList();
Children.ForEach(c => c.Order());
}
public void Sum() => Size = Children?.Sum(x => x.Size) ?? 0;
public void WriteResults(StreamWriter fs, int level =0)
{
fs.WriteLine($"{new string(' ', level)}{Name} {Size.ToSize(3)}");
level++;
if (Children == null) return;
foreach (var info in Children)
info.WriteResults(fs, level);
}
}
Использование
public static void Main(string[] args)
{
var info = ProcessDirectory(new DirectoryInfo(@"D:\"));
using (var fs = new FileStream(@"D:\Reuslts.txt", FileMode.Create))
{
using (var sw = new StreamWriter(fs))
{
info.Sum();
info.Order();
info.WriteResults(sw);
}
}
}
private static Info ProcessDirectory(DirectoryInfo directoryInfo)
{
var baseInfo = new Info(directoryInfo);
var queue = new Queue<Info>();
queue.Enqueue(baseInfo);
while (queue.Count>0)
{
try
{
var info = queue.Dequeue();
foreach (var dir in info.GetDirectories())
queue.Enqueue(dir);
}
catch (UnauthorizedAccessException e) { }
}
return baseInfo;
}