Unity 获取缓存大小

一、需求

有时候我们需要在设置界面中显示当前下载或缓存的文件数据大小。
例如:
在这里插入图片描述

二、代码实现

public static int GetCacheSize(string folder)
 {
    
    
      string path = Path.Combine(Application.persistentDataPath,folder);
      Debug.Log("path = " + path);
      DirectoryInfo levelDirectoryPath = new DirectoryInfo(path);
      FileInfo[] fileInfo = levelDirectoryPath.GetFiles("*.*", SearchOption.AllDirectories);
      // int i = 0;
      int size = 0;
      foreach (FileInfo file in fileInfo)
      {
    
    
          // i++;
          size += (int)file.Length;
          // etc etc
          // Debug.Log("files [" + i + "] :" + file.Name
          //     + "///file.Length:" + file.Length
          //     + "///file.LastAccessTime:" + file.LastAccessTime
          //     + "///file.DirectoryName:" + file.DirectoryName
          //     + "///file.Directory:" + file.Directory);
      }
      return size;
  }

三、注意

file.Length 获取的大小为byte,需要根据需求转换

  • 转换方案
/// <summary>字节单位换算</summary>
  public static string ByteConversion(double length)
  {
    
    
      string temp;
      if (length < 1024)
      {
    
    
          temp = Math.Round(length, 0) + "B";
      }
      else if (length < 1024 * 1024)
      {
    
    
          temp = Math.Round(length / (1024), 0) + "KB";
      }
      else if (length < 1024 * 1024 * 1024)
      {
    
    
          temp = Math.Round(length / (1024 * 1024), 2) + "MB";
      }
      else
      {
    
    
          temp = Math.Round(length / (1024 * 1024 * 1024), 2) + "GB";
      }
      return temp;
  }

猜你喜欢

转载自blog.csdn.net/weixin_56130753/article/details/126343126