马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

C# calculate disk size

  [复制链接]
查看2545 | 回复19 | 2019-11-21 22:00:32 | 显示全部楼层 |阅读模式
  1. static void Main(string[] args)
  2. {
  3. string dir = @"C:";
  4. string[] dirs=Directory.GetDirectories(dir);
  5. long totalSize = 0;
  6. if(dirs!=null && dirs.Any())
  7. {
  8. foreach(string dr in dirs)
  9. {
  10. var size = new DirectoryInfo(dr).GetDirectorySize();
  11. totalSize += size;
  12. Console.WriteLine($"dir:{dr},size:{size}");
  13. }
  14. }
  15. Console.WriteLine($"totalSize:{totalSize}");
  16. System.Diagnostics.Debug.WriteLine($"totalSize:{totalSize}");
  17. }
  18. static class DirHelper
  19. {
  20. public static long GetDirectorySize(this System.IO.DirectoryInfo directoryInfo, bool recursive = true)
  21. {
  22. var startDirectorySize = default(long);
  23. try
  24. {
  25. if (directoryInfo == null || !directoryInfo.Exists)
  26. return startDirectorySize; //Return 0 while Directory does not exist.
  27. //Add size of files in the Current Directory to main size.
  28. foreach (var fileInfo in directoryInfo.GetFiles())
  29. System.Threading.Interlocked.Add(ref startDirectorySize, fileInfo.Length);
  30. if (recursive) //Loop on Sub Direcotries in the Current Directory and Calculate it's files size.
  31. System.Threading.Tasks.Parallel.ForEach(directoryInfo.GetDirectories(), (subDirectory) =>
  32. System.Threading.Interlocked.Add(ref startDirectorySize, GetDirectorySize(subDirectory, recursive)));
  33. //Return full Size of this Directory.
  34. }
  35. catch
  36. {
  37. }
  38. return startDirectorySize;
  39. }
  40. }
复制代码

  1. static void DiskDemo()
  2. {
  3. string dir = @"C:\Windows";
  4. string[] dirs = Directory.GetDirectories(dir);
  5. long totalSize = 0;
  6. StringBuilder builder = new StringBuilder();
  7. List<Dir> dirList = new List<Dir>();
  8. if (dirs != null && dirs.Any())
  9. {
  10. foreach (string dr in dirs)
  11. {
  12. var size = new DirectoryInfo(dr).GetDirectorySize();
  13. Dir d = new Dir();
  14. d.DirName = dr;
  15. d.DirSize = size;
  16. dirList.Add(d);
  17. totalSize += size;
  18. }
  19. }
  20. foreach (var dd in dirList.OrderByDescending(x => x.DirSize))
  21. {
  22. System.Diagnostics.Debug.WriteLine(dd);
  23. Console.WriteLine(dd);
  24. }
  25. System.Diagnostics.Debug.WriteLine($"totalSize:{totalSize}");
  26. }
  27. class Dir
  28. {
  29. public string DirName { get; set; }
  30. public long DirSize { get; set; }
  31. public override string ToString()
  32. {
  33. return $"DirName:{DirName},DirSize:{DirSize}";
  34. }
  35. }
复制代码

*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则