Is it possible to extend File Class? I would like to add new GetFileSize Method to File Class and use it like this
string s = File.GetFileSize("c:\MyFile.txt");
Implementation
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";
}
}
I have tried to use Extension Methods to add the method to File Class but compiler give error “‘System.IO.File’: static types cannot be used as parameters”
No, but you can just create your own static class and put your methods there. Given that you are basically producing a summary string for your user interface, I wouldn’t think that it would belong within the File class anyway (even if you could put it there – which you can’t).