你如何在C#中获取文件大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1380839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:52:32  来源:igfitidea点击:

How do you get the file size in C#?

c#filesize

提问by JL.

I need a way to get the size of a file using C#, and not the size on disk. How is this possible?

我需要一种使用 C# 获取文件大小的方法,而不是磁盘上的大小。这怎么可能?

Currently I have this loop

目前我有这个循环

foreach (FileInfo file in downloadedMessageInfo.GetFiles())
{
    //file.Length (will this work)
}

Will this return the size or the size on disk?

这会返回磁盘上的大小或大小吗?

采纳答案by Marcin Deptu?a

FileInfo.Lengthwill return the length of file, in bytes (not size on disk), so this is what you are looking for, I think.

FileInfo.Length将返回文件的长度,以字节为单位(不是磁盘上的大小),所以这就是你要找的,我想。

回答by Thomas Levesque

It returns the file contents length

它返回文件内容长度

回答by jason

FileInfo.Lengthwill do the trick (per MSDN it "[g]ets the size, in bytes, of the current file.") There is a nice pageon MSDN on common I/O tasks.

FileInfo.Length会做到这一点(根据 MSDN,它“[g] 获取当前文件的大小(以字节为单位)。”)MSDN 上有一个关于常见 I/O 任务的不错的页面

回答by Austin Salonen

MSDN FileInfo.Lengthsays that it is "the size of the current file in bytes."

MSDN FileInfo.Length说它是“当前文件的大小(以字节为单位)”。

My typical Google search for something like this is: msdn FileInfo

我典型的谷歌搜索是这样的: msdn FileInfo

回答by Charlie Salts

Size on disk might be different, if you move the file to another filesystem (FAT16, NTFS, EXT3, etc)

如果您将文件移动到另一个文件系统(FAT16、NTFS、EXT3 等),磁盘上的大小可能会有所不同

As other answerers have said, this will give you the size in bytes, not the size on disk.

正如其他回答者所说,这将为您提供以字节为单位的大小,而不是磁盘上的大小。

回答by live-love

If you have already a file path as input, this is the code you need:

如果您已经有一个文件路径作为输入,这是您需要的代码:

long length = new System.IO.FileInfo(path).Length;