简体   繁体   English

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

[英]How to get Size of file in FileInfo?

I want to get the size to show in the ListView. 我想获得ListView中显示的大小。 But my code return 0. I find.Length() get length size but only have Count() and it can't resolve my problem. 但我的代码返回0.我发现.Length()得到长度大小但只有Count(),它无法解决我的问题。

My code like: 我的代码如下:

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.

You are using fileInfos , which is a List<T> . 您正在使用fileInfos ,它是List<T> You want to check the length of your actual FileInfo f : 您想检查实际FileInfo f的长度:

long s1 = f.Length;

While you are dividing by 1024, please note, that there is a difference in units when dealing with filezises, depending on your base: 2 or 10. KB is 2^x and kB is 10^x bytes. 当你除以1024时,请注意,处理filezises时单位有所不同,具体取决于你的基数:2或10. KB是2 ^ x,kB是10 ^ x字节。

you can get the file size in bytes using Length 您可以使用Length获取文件大小(以字节为单位)

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

The long s1 = fileInfos.Count; long s1 = fileInfos.Count; doesn't check the file length. 不检查文件长度。 It checks the number of members of the fileInfos List . 它检查fileInfos List的成员数。 If you want to get individual file length of the files in your List . 如果要获取List文件的单个文件长度。 Do this: 做这个:

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

or in your loop 或者在你的循环中

long fileLength = f.Length;

Also, beware of your operation: 另外,请注意您的操作:

s1 = s1/1024;

Since s1 is a long , you will lose some precision here... maybe you can consider to use decimal for s1 from the beginning 由于s1是一个long ,在这里你会失去一些精密...也许你可以考虑使用decimals1从一开始就

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

would give the size of the file. 会给出文件的大小。 It is better to check whether the file exists or not before getting the size to avoid FileNotFound exception. 在获取大小以避免FileNotFound异常之前,最好检查文件是否存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM