C#无法将FileSize从字节转换为GB

Phi*_*ilo 1 c# filesize

我用C语言计算文件大小: -

 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
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将其转换为GB时: -

x/ (1024 * 1024 * 1024)
Run Code Online (Sandbox Code Playgroud)

我总是得到0作为答案.我假设这与x的数据类型有关.有人可以帮我理解这个吗?

Joe*_*orn 5

它正在进行整数除法.对于任何小于1GB的东西你都会看到0,甚至超过你还会看到整数.试试这个:

x/ (1024.0 * 1024.0 * 1024.0)
Run Code Online (Sandbox Code Playgroud)

要么

x/ (1024D * 1024D * 1024D)
Run Code Online (Sandbox Code Playgroud)

并确保将结果放入支持浮点值的内容中.可能你可以改变:

var x = 
Run Code Online (Sandbox Code Playgroud)

double x = 
Run Code Online (Sandbox Code Playgroud)