我需要一种使用 C# 获取文件大小的方法,而不是磁盘上的大小。这怎么可能?
目前我有这个循环
foreach (FileInfo file in downloadedMessageInfo.GetFiles())
{
//file.Length (will this work)
}
这会返回大小还是磁盘上的大小?
如果您已经有一个文件路径作为输入,那么这就是您需要的代码:
long length = new System.IO.FileInfo(path).Length;
FileInfo.Length
将返回文件的长度,以字节为单位(而不是磁盘上的大小),所以我认为这就是您正在寻找的。
MSDN FileInfo.Length 说它是“当前文件的大小(以字节为单位)。”
我典型的 Google 搜索类似内容是:msdn FileInfo
FileInfo 类的 Length 属性返回文件的大小(而不是磁盘上的大小)。如果您想要格式化的文件大小(即 15 KB)而不是长字节值,您可以使用 CSharpLib,这是我制作的一个包,为 FileInfo 类添加了更多功能。这是一个例子:
using CSharpLib;
FileInfo info = new FileInfo("sample.txt");
Console.WriteLine(info.FormatBytes()); // Output: 15 MB
它返回文件内容长度
如果将文件移动到另一个文件系统(FAT16、NTFS、EXT3 等),磁盘上的大小可能会有所不同
正如其他回答者所说,这将为您提供以字节为单位的大小,而不是磁盘上的大小。
long l = new System.IO.FileInfo(path).Length;
string l_ = Formatter(l); // Example: "67 Mb"
//
public string Formatter(long input)
{
string output;
switch (input.ToString().Length)
{
case > 12:
output = input / 1000000000000 + " Tb";
break;
case > 9:
output = input / 1000000000 + " Gb";
break;
case > 6:
output = input / 1000000 + " Mb";
break;
case > 3:
output = input / 1000 + " Kb";
break;
default:
output = input + " b";
break;
}
return output;
}