var length = new System.IO.FileInfo(path).Length;
This gives the logical size of the file, not the size on the disk.
I wish to get the size of a file on the disk in C# (preferably without interop) as would be reported by Windows Explorer.
It should give the correct size, including for:
- A compressed file
- A sparse file
- A fragmented file
According to MSDN social forums:
See How to get the size on disk of a file in C#.
But please note the point that this will not work in NTFS where compression is switched on.
I think it will be like this:
I'm still doing some testing for this, to get a confirmation.
This uses GetCompressedFileSize, as ho1 suggested, as well as GetDiskFreeSpace, as PaulStack suggested, it does, however, use P/Invoke. I have tested it only for compressed files, and I suspect it does not work for fragmented files.
The code above does not work properly on Windows Server 2008 or 2008 R2 or Windows 7 and Windows Vista based systems as cluster size is always zero (GetDiskFreeSpaceW and GetDiskFreeSpace return -1 even with UAC disabled.) Here is the modified code that works.
C#
VB.NET