Search code examples
c#filesize

C# Unable to convert FileSize from Bytes to GB


I am calculating file size in C# using: -

 FileInfo info = new FileInfo(file);
 uint dummy, sectorsPerCluster, bytesPerSector;
 int result = GetDiskFreeSpaceW(info.Directory.Root.FullName, 
                    out sectorsPerCluster, out bytesPerSector, out dummy, out dummy);
 if (result == 0) throw new Win32Exception();
 uint clusterSize = sectorsPerCluster * bytesPerSector;
 uint hosize;
 uint losize = GetCompressedFileSizeW(file, out hosize);
 long size;
 size = (long)hosize << 32 | losize;
 var x = (((size + clusterSize - 1) / clusterSize) * clusterSize);  // in bytes

However when I try to convert that into GB:-

x/ (1024 * 1024 * 1024)

I always get 0 as the answer. I am assuming that this has to do with the data type of x. Can someone help me with understand this?


Solution

  • It's doing integer division. You're gonna see a 0 for anything less than 1GB, and even beyond that you'll still only see whole numbers. Try this:

    x/ (1024.0 * 1024.0 * 1024.0)
    

    or

    x/ (1024D * 1024D * 1024D)
    

    And make sure you're putting the result into something that supports floating point values. Possibly you can just change:

    var x = 
    

    to

    double x =