开发者

Extend File Class

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:##.##} B开发者_Python百科ytes", 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"


Wouldn't this simpler

System.IO.FileInfo f1 = new System.IO.FileInfo("c:\\myfile.txt").Length 

or you can extend the FileInfo class

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";
  }
 }

And use it like

 System.IO.FileInfo f1 = new System.IO.FileInfo("c:\\myfile.txt");
 var size = f1.GetFileSize();


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).


File is a static class and cannot be extended. Use something like FileEx instead.

string s = FileEx.GetFileSize("something.txt");


No, you can't do that. Just create your own static class and add that method to it.


Looks like you're gonna have to just implement that as your own file helper.

You could make it an extension method of FileInfo if you wanted but then you'd have to do something like.

new FileInfo("some path").GetFileSize();


You can either implement a new static class that would have such a method or extent a non-static class like FileStream.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜