CommonUtils.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System;
  2. using System.IO;
  3. namespace Asset_Cleaner {
  4. static class CommonUtils {
  5. static string[] _suffix = {"B", "KB", "MB", "GB", "TB"};
  6. public static string BytesToString(long byteCount) {
  7. if (byteCount == 0)
  8. return $"0 {_suffix[0]}";
  9. var bytes = Math.Abs(byteCount);
  10. var place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
  11. double num;
  12. if (place == 0 || place == 1) { // display B, KB in MB
  13. num = Math.Round(bytes / Math.Pow(1024, 2), 4);
  14. return $"{Math.Sign(byteCount) * num:N} {_suffix[2]}";
  15. }
  16. num = Math.Round(bytes / Math.Pow(1024, place), 1);
  17. return $"{Math.Sign(byteCount) * num:F0} {_suffix[place]}";
  18. }
  19. // todo
  20. public static long Size(string path) {
  21. return TryGetSize(path, out var res) ? res : 0L;
  22. }
  23. public static bool TryGetSize(string path, out long result) {
  24. if (!File.Exists(path)) {
  25. result = default;
  26. return false;
  27. }
  28. var fi = new FileInfo(path);
  29. result = fi.Length;
  30. return true;
  31. }
  32. }
  33. }