2011-03-15 114 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();