C# 如何将文件大小以字节为单位正确转换为兆字节或千兆字节?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/565704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:23:45  来源:igfitidea点击:

How to correctly convert filesize in bytes into mega or gigabytes?

c#bytediskdriveinfomegabyte

提问by Mats

I'm using the DriveInfo class in my C# project to retrieve the available bytes on given drives. How to I correctly convert this number into Mega- or Gigabytes? Dividing by 1024 will not do the job I guess. The results always differ from those shown in the Windows-Explorer.

我在我的 C# 项目中使用 DriveInfo 类来检索给定驱动器上的可用字节。如何正确地将此数字转换为兆字节或千兆字节?我想除以 1024 不会完成这项工作。结果总是与 Windows 资源管理器中显示的结果不同。

采纳答案by Adam Davis

1024 is correct for usage in programs.

1024 适合在程序中使用。

The reason you may be having differences is likely due to differences in what driveinfo reports as "available space" and what windows considers available space.

您可能有差异的原因可能是由于 driveinfo 报告为“可用空间”的内容和 Windows 认为可用空间的内容不同。

Note that only drive manufacturers use 1,000. Within windows and most programs the correct scaling is 1024.

请注意,只有驱动器制造商使用 1,000。在 Windows 和大多数程序中,正确的缩放比例是 1024。

Also, while your compiler should optimize this anyway, this calculation can be done by merely shifting the bits by 10 for each magnitude:

此外,尽管您的编译器无论如何都应该对此进行优化,但只需将每个幅度的位移动 10 即可完成此计算:

KB = B >> 10
MB = KB >> 10 = B >> 20
GB = MB >> 10 = KB >> 20 = B >> 30

KB = B >> 10
MB = KB >> 10 = B >> 20
GB = MB >> 10 = KB >> 20 = B >> 30

Although for readability I expect successive division by 1024 is clearer.

虽然为了可读性,我希望连续除以 1024 更清晰。

回答by Fabian Vilers

Divide by 1024.

除以 1024。

回答by EBGreen

It depends on if you want the actual file size or the size on disk. The actual file size is the actual number of bytes that the file uses in memory. The size on disk is a function of the file size and the block size for your disk/file system.

这取决于您想要实际的文件大小还是磁盘上的大小。实际文件大小是文件在内存中使用的实际字节数。磁盘大小是文件大小和磁盘/文件系统的块大小的函数。

回答by starblue

XKCD has the definite answer:

XKCD有明确的答案

Single, definitive standard for KB

KB 的单一、权威标准

回答by starblue

1024 is actually wrong. The International Engineering Community (IEC) has developed a standard in 2000, which is sadly being ignored by the computer industry. This standard basically says that

1024其实是错误的。国际工程界 (IEC) 于 2000 年制定了一项标准,遗憾的是它被计算机行业忽视了。这个标准基本上是说

  • 1000 bytes is a kilobyte, 1000KB are one MB and so on. The abbreviations are KB, MB, GB and so on.
  • The widely used 1024 bytes = 1 kilobyte should instead by called 1024 bytes = 1 Kibibyte (KiB), 1024 KiB = 1 Mebibyte (MiB), 1024 MiB = 1 Gibibyte (GiB) and so on.
  • 1000 字节是千字节,1000KB 是 1 MB,依此类推。缩写有KB、MB、GB等。
  • 广泛使用的 1024 字节 = 1 KB 应改为称为 1024 字节 = 1 Kibibyte (KiB)、1024 KiB = 1 Mebibyte (MiB)、1024 MiB = 1 Gibibyte (GiB) 等等。

You can all read it up on the IEC SI zone.

您都可以在IEC SI 专区阅读

So in order for your conversions to be correct and right according to international standardization you should use this scientific notation.

因此,为了使您的转换根据国际标准化正确且正确,您应该使用这种科学记数法。

回答by Anders

I have a faint recollection that the answer on whether to use 1000 or 1024 lies in the casing of the prefix. Example: If the "scientific" 1000 scaling is used, then the "scientific" unit will be kB (just as in kg, kN etc). If the computer centric 1024 scaling is used, then the unit will be KB. So, uppercasing the scientific prefix makes it computer centric.

我隐约记得,使用1000还是1024的答案在于前缀的大小写。示例:如果使用“科学”1000 标度,则“科学”单位将是 kB(就像 kg、kN 等)。如果使用以计算机为中心的 1024 缩放,则单位为 KB。因此,大写科学前缀使其以计算机为中心。

回答by AZ_

/// <summary>
/// Function to convert the given bytes to either Kilobyte, Megabyte, or Gigabyte
/// </summary>
/// <param name="bytes">Double -> Total bytes to be converted</param>
/// <param name="type">String -> Type of conversion to perform</param>
/// <returns>Int32 -> Converted bytes</returns>
/// <remarks></remarks>
public static double ConvertSize(double bytes, string type)
{
    try
    {
        const int CONVERSION_VALUE = 1024;
        //determine what conversion they want
        switch (type)
        {
            case "BY":
                 //convert to bytes (default)
                 return bytes;
                 break;
            case "KB":
                 //convert to kilobytes
                 return (bytes / CONVERSION_VALUE);
                 break;
            case "MB":
                 //convert to megabytes
                 return (bytes / CalculateSquare(CONVERSION_VALUE));
                 break;
            case "GB":
                 //convert to gigabytes
                 return (bytes / CalculateCube(CONVERSION_VALUE));
                 break;
            default:
                 //default
                 return bytes;
                 break;
          }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return 0;
      }
}

/// <summary>
/// Function to calculate the square of the provided number
/// </summary>
/// <param name="number">Int32 -> Number to be squared</param>
/// <returns>Double -> THe provided number squared</returns>
/// <remarks></remarks>
public static double CalculateSquare(Int32 number)
{
     return Math.Pow(number, 2);
}


/// <summary>
/// Function to calculate the cube of the provided number
/// </summary>
/// <param name="number">Int32 -> Number to be cubed</param>
/// <returns>Double -> THe provided number cubed</returns>
/// <remarks></remarks>
public static double CalculateCube(Int32 number)
{
     return Math.Pow(number, 3);
}

//Sample Useage
String Size = "File is " + ConvertSize(250222,"MB") + " Megabytes in size"