Getting a File's size on disk

After a few hours of wondering why a FileStream read was failing on a parse I found that the length I was getting wasn't the length to expect. On right-click of an image file in Windows Explorer you can see 'Size' and 'Size on disk:'
The value I need to get from my C# application is the 'Size on disk:' - I have done a dozen tests and sure enough this is the crux of my problem -- so how do I get the 'Size on disk:' from .NET

Thanx,


Answer this question

Getting a File's size on disk

  • N30

    A third party lib fails if you pass in a length that is not the 'size on disk'

    Given the OS can report this proprtyle fairly easy I am a little surprised it is made so impossible from .NET or even the Win API.

  • ulven

    I'm interested in why you need to the length of the file to read the Stream.

    FileStream.Read will only return as many bytes as there are available. It's return value will be 0 when you have reached the end of the stream.

  • Frankiee

    When reading the contents of a file, you don't need to know the size on disk. A file might have just one byte of contents, but it might take up 512 bytes on the disk (or more, depending on the file system and formatting options). The remaining 511 bytes are in an undefined state and cannot be read.

  • Roland Hasenohrl

    As others have said the size on disk is the actual size of the file on disk and is dependent upon file cluster size.  It doesn't mean your file actually takes up that much.  In fact if you are using compression then you'll find that it is actually less than the actual size of the file.  What you care about is the size of the file.  This is the actual (stream) size of the file. 

    When working with a StreamReader you can get the actual size of the file (what you want) through the BaseStream.Length property.  For IStream classes it is simply the Length property.  For an arbitrary file you can use FileInfo.Length.  These return the actual file size and not the size of the file on disk.

    If you want the size of the file on disk when compressed or sparse then you have to use Platform/Invoke to call GetCompressedFileSize as I don't believe .NET exposes this method directly.  Furthermore this doesn't give you the actual size on disk if it isn't compressed.  For that I believe you'd have to determine how many clusters it takes up and multiply that by the cluster size.  I don't believe there is any direct way in Windows to do that but WMI might provide a way.  Nevertheless this is not what you'd want to use as it'll also contain unused bytes of data.

    Michael Taylor - 11/20/05

  • Bill Rubin

    NOTE: I have found that the reported size for files on rewriteable CD's with 1.1 isnt accurate.  I never got to the bottom of it but it seemed to be the size on disk that was reported.

    This has no bearing on this discussion directly I think but might be of interest anyway.

  • Getting a File's size on disk