如何在FileInfo中获取文件大小?

时间:2016-01-25 06:50:39

标签: c#

我想获得ListView中显示的大小。 但我的代码返回0.我发现.Length()得到长度大小但只有Count(),它无法解决我的问题。

我的代码如下:

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.

4 个答案:

答案 0 :(得分:6)

您使用的是fileInfosList<T>。您想检查实际FileInfo f的长度:

long s1 = f.Length;

当你除以1024时,请注意,处理filezises时单位有所不同,具体取决于你的基数:2或10. KB是2 ^ x,kB是10 ^ x字节。

答案 1 :(得分:1)

您可以使用Length

获取以字节为单位的文件大小
FileInfo f = new FileInfo(filePath);
long fileSize = f.Length;

答案 2 :(得分:1)

long s1 = fileInfos.Count;不检查文件长度。它会检查fileInfos List的成员数量。如果您想获得List中文件的单个文件长度。这样做:

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

或在你的循环中

long fileLength = f.Length;

另外,请注意您的操作:

s1 = s1/1024;

由于s1long,你在这里会失去一些精确性......也许你可以考虑从decimal开始使用s1

答案 3 :(得分:1)

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

会给出文件的大小。在获取大小以避免FileNotFound异常之前,最好检查文件是否存在。