【发布时间】:2011-07-15 18:45:57
【问题描述】:
是否可以扩展文件类?我想将新的 GetFileSize 方法添加到文件类并像这样使用它
string s = File.GetFileSize("c:\MyFile.txt");
实施
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";
}
}
我尝试使用扩展方法将方法添加到文件类,但编译器给出错误“'System.IO.File':静态类型不能用作参数”
【问题讨论】: