[英]How to get Size of file in FileInfo?
我想获得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.
您正在使用fileInfos
,它是List<T>
。 您想检查实际FileInfo f
的长度:
long s1 = f.Length;
当你除以1024时,请注意,处理filezises时单位有所不同,具体取决于你的基数:2或10. KB是2 ^ x,kB是10 ^ x字节。
您可以使用Length
获取文件大小(以字节为单位)
FileInfo f = new FileInfo(filePath);
long fileSize = f.Length;
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;
由于s1
是一个long
,在这里你会失去一些精密...也许你可以考虑使用decimal
为s1
从一开始就
FileInfo fileInfo = new FileInfo(path);
long fileLength = fileInfo.Length;
会给出文件的大小。 在获取大小以避免FileNotFound异常之前,最好检查文件是否存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.