1

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?

Philo
  • 1,931
  • 12
  • 39
  • 77
  • What data type is x, and what is the value of x? – Haukman May 01 '17 at 16:56
  • @Haukman type of `x` is long as shown in the code in the post... – Alexei Levenkov May 01 '17 at 16:58
  • 1
    Side note: Philo, you may want to re-read [MCVE] guidance. Something like `long x = 123; Console.Write(x/(1024*1024*1024);` would be much better example of the problem. – Alexei Levenkov May 01 '17 at 17:00
  • No, you have it as a 'var', which isn't clear unless you put this in a compiler. Also it would've helped if you included the value of x, i.e. what would Console.WriteLine(x) show. – Haukman May 01 '17 at 19:41

1 Answers1

5

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 = 
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794