2011-03-15 70 views
2

是否可以扩展文件类?我想补充新GetFileSize方法File类和使用它像这样扩展文件类

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':静态类型不能用作参数“

回答

4

不,但您可以创建自己的静态类并将您的方法放在那里。鉴于您基本上为您的用户界面生成了一个摘要字符串,我不认为它会属于File类(即使您可以将它放在那里 - 你不能)。

0

不,你不能这样做。只需创建您自己的静态类并将其添加到它。

+0

请说明您downvote。 – 2012-11-13 20:07:52

0

看起来你必须把它作为你自己的文件助手来实现。

如果你想要的话,你可以使它成为FileInfo的扩展方法,但是你必须做类似的事情。

new FileInfo(“some path”)。GetFileSize();

3

Filestatic类,不能扩展。改为使用类似FileEx的东西。

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

您可以实现一个新的静态类,该静态类可以有一个非静态类,如FileStream

4

这是不是简单

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

,也可以扩展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"; 
    } 
} 

而且使用它像

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