2016-01-25 13 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异常之前,最好检查文件是否存在。