如何从1024到1kb解析文件的大小?一旦我为它创建了一个函数,就像30行一样充满了if.有更"优雅"的方式吗?我需要使用什么?1kb = 1000b或1kb = 1024b?
这个解决方案看起来并不合理.它有点长,但它确实迎合了exa/petabytes!
// Returns the human-readable file size for an arbitrary, 64-bit file size
// The default format is "0.### XB", e.g. "4.2 KB" or "1.434 GB"
public static string GetSizeReadable(long i)
{
string sign = (i < 0 ? "-" : "");
double readable = (i < 0 ? -i : i);
string suffix;
if (i >= 0x1000000000000000) // Exabyte
{
suffix = "EB";
readable = (double)(i >> 50);
}
else if (i >= 0x4000000000000) // Petabyte
{
suffix = "PB";
readable = (double)(i >> 40);
}
else if (i >= 0x10000000000) // Terabyte
{
suffix = "TB";
readable = (double)(i >> 30);
}
else if (i >= 0x40000000) // Gigabyte
{
suffix = "GB";
readable = (double)(i >> 20);
}
else if (i >= 0x100000) // Megabyte
{
suffix = "MB";
readable = (double)(i >> 10);
}
else if (i >= 0x400) // Kilobyte
{
suffix = "KB";
readable = (double)i;
}
else
{
return i.ToString(sign + "0 B"); // Byte
}
readable = readable / 1024;
return sign + readable.ToString("0.### ") + suffix;
}
Run Code Online (Sandbox Code Playgroud)
建议将上述函数作为公共静态方法放在帮助器或实用程序类中.
// EXAMPLE OUTPUT
GetSizeReadable(1023); // 1023 B
GetSizeReadable(1024); // 1 KB
GetSizeReadable(1025); // 1.001 KB
// Example of getting a file size and converting it to a readable value
string fileName = "abc.txt";
long fileSize = new System.IO.FileInfo(fileName).Length;
string sizeReadable = GetSizeReadable(fileSize);
Run Code Online (Sandbox Code Playgroud)
也许是这样的?
public string FileSizeAsString(long lengthOfFile)
{
string[] sizes = { "bytes", "KB", "MB", "GB" };
int j = 0;
while (lengthOfFile > 1024 && j < sizes.Length)
{
lengthOfFile = lengthOfFile / 1024;
j++;
}
return (lengthOfFile + " " + sizes[j]);
}
Run Code Online (Sandbox Code Playgroud)
用法:
Console.WriteLine(FileSizeAsString(new FileInfo(@"C:\\your_file_here.ext").Length));
Run Code Online (Sandbox Code Playgroud)
您可以根据需要展开字符串数组sizes,它将继续计算.