Problem
I’m looking for a technique to get the size of a file in C# rather than the size on disk. What gives that this is possible?
I’m currently stuck in a loop.
foreach (FileInfo file in downloadedMessageInfo.GetFiles())
{
//file.Length (will this work)
}
Will the size or the size on disk be returned?
Asked by JL.
Solution #1
This is the code you require if you already have a file path as input:
long length = new System.IO.FileInfo(path).Length;
Answered by live-love
Solution #2
FileInfo.Length returns the file’s length in bytes (not the size on disk), so I believe this is what you’re looking for.
Answered by Marcin DeptuĆa
Solution #3
FileInfo.Length will suffice (per MSDN it “[g]ets the size, in bytes, of the current file.”) On MSDN, there’s an excellent page about common I/O chores.
Answered by jason
Solution #4
According to MSDN, FileInfo.Length is “the current file’s size in bytes.”
For stuff like this, I usually go to Google and type in msdn FileInfo.
Answered by Austin Salonen
Solution #5
The Length field of the FileInfo class returns the file’s size (not the size on disk). You can use CSharpLib, a package I created that extends the FileInfo class with more features, to get a formatted file size (e.g. 15 KB) instead of a lengthy byte number. Here’s an illustration:
using CSharpLib;
FileInfo info = new FileInfo("sample.txt");
Console.WriteLine(info.FormatBytes()); // Output: 15 MB
Answered by S. Ferrell
Post is based on https://stackoverflow.com/questions/1380839/how-do-you-get-the-file-size-in-c