2016-01-25 15 views
3

我想獲得在ListView中顯示的大小。 但我的代碼返回0.我find.Length()獲取長度大小,但只有Count(),它不能解決我的問題。如何獲取FileInfo中文件的大小?

我的代碼,如:

string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop, false); 
List<FileInfo> fileInfos = new List<FileInfo>(); 
foreach (string filePath in filePaths) 
{ 
    FileInfo f = new FileInfo(filePath); 
    fileInfos.Add(f); 
    long s1 = fileInfos.Count; 
    string chkExt = Path.GetExtension(f.ToString()); 
    s1 = s1/1024; 
    decimal d = default(decimal); 
    d = decimal.Round(s1, 2, MidpointRounding.AwayFromZero); 
    // d is 0. Because s1 = 1 only count not length of file. 
+1

使用長度。也是整數除法; make 1024.0 –

+1

'FileInfo'具有'Length'屬性。它返回文件的字節數。 – daniel59

+0

'fileInfos.Count'給出您讀取的文件信息的數量。因此,對於第1024個文件的文件,它將返回0.在那之後,1等。您在那裏使用了錯誤的編號。您應該在'f'中查找長度或大小屬性,這是當前文件的實際文件信息。也許可以改進命名,這樣可以降低再次發生此類錯誤的風險。 – GolezTrol

回答

6

您正在使用fileInfos,這是一個List<T>。要檢查您的實際的FileInfo f長度:

long s1 = f.Length; 

雖然你是1024分,請注意,存在與filezises打交道時,根據您的基礎上,在單位的差異:2或10。 KB是2^x並且kB是10^x字節。

+0

謝謝。是工作。 – terri

1

您可以使用Length

FileInfo f = new FileInfo(filePath); 
long fileSize = f.Length; 
+1

謝謝你的回答。 – terri

1

long s1 = fileInfos.Count;不檢查文件長度得到以字節爲單位的文件大小。它會檢查fileInfosList的成員數量。如果您想要獲得List中文件的單個文件長度。這樣做:

int index = 0; //zero is an example 
long fileLength = fileInfos[index].Length; 

或在循環

long fileLength = f.Length; 

而且,當心你的操作:

s1 = s1/1024; 

由於s1long,在這裏你會失去一些精密...也許你可以考慮使用decimal來代替s1

1
FileInfo fileInfo = new FileInfo(path); 
long fileLength = fileInfo.Length; 

會給出文件的大小。在獲取大小以避免FileNotFound異常之前,最好檢查文件是否存在。