[c#] How do you get the file size in C#?

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

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?

This question is related to c# filesize

The answer is


It returns the file contents length


The FileInfo class' Length property returns the size of the file (not the size on disk). If you want a formatted file size (i.e. 15 KB) rather than a long byte value you can use CSharpLib, a package I've made that adds more functionality to the FileInfo class. Here's an example:

using CSharpLib;
FileInfo info = new FileInfo("sample.txt");
Console.WriteLine(info.FormatBytes());  // Output: 15 MB

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

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

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

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


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


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

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