扩展文件类

Tom*_*mas 3 c# class extend

是否可以扩展文件类?我想向文件类添加新的 GetFileSize 方法并像这样使用它

string s = File.GetFileSize("c:\MyFile.txt");
Run Code Online (Sandbox Code Playgroud)

执行

public static string GetFileSize(string fileName)
{

    FileInfo fi = new FileInfo(fileName);
    long Bytes = fi.Length;

    if (Bytes >= 1073741824)
    {
        Decimal size = Decimal.Divide(Bytes, 1073741824);
        return String.Format("{0:##.##} GB", size);
    }
    else if (Bytes >= 1048576)
    {
        Decimal size = Decimal.Divide(Bytes, 1048576);
        return String.Format("{0:##.##} MB", size);
    }
    else if (Bytes >= 1024)
    {
        Decimal size = Decimal.Divide(Bytes, 1024);
        return String.Format("{0:##.##} KB", size);
    }
    else if (Bytes > 0 & Bytes < 1024)
    {
        Decimal size = Bytes;
        return String.Format("{0:##.##} Bytes", size);
    }
    else
    {
        return "0 Bytes";
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用扩展方法将方法添加到文件类,但编译器给出错误“'System.IO.File':静态类型不能用作参数”

Ram*_*Vel 5

这不是更简单吗

System.IO.FileInfo f1 = new System.IO.FileInfo("c:\\myfile.txt").Length 
Run Code Online (Sandbox Code Playgroud)

或者你可以扩展 FileInfo 类

public static string GetFileSize(this FileInfo fi)
{

  long Bytes = fi.Length;

  if (Bytes >= 1073741824)
  {
     Decimal size = Decimal.Divide(Bytes, 1073741824);
     return String.Format("{0:##.##} GB", size);
  }
  else if (Bytes >= 1048576)
  {
     Decimal size = Decimal.Divide(Bytes, 1048576);
     return String.Format("{0:##.##} MB", size);
  }
  else if (Bytes >= 1024)
  {
     Decimal size = Decimal.Divide(Bytes, 1024);
     return String.Format("{0:##.##} KB", size);
  }
  else if (Bytes > 0 & Bytes < 1024)
  {
     Decimal size = Bytes;
     return String.Format("{0:##.##} Bytes", size);
  }
  else
  {
     return "0 Bytes";
  }
 }
Run Code Online (Sandbox Code Playgroud)

并使用它

 System.IO.FileInfo f1 = new System.IO.FileInfo("c:\\myfile.txt");
 var size = f1.GetFileSize();
Run Code Online (Sandbox Code Playgroud)