通过FileInfo类获得的文件大小是long类型的,并非我们习惯的格式,因此为long类型添加一个扩展方法:
public static string ToFriendlyFileSize(this double arg) {
string result = "N/A";
double size = arg;
const double p1 = 1024;
const double p2 = 1048576; // Math.Pow(1024,2)
const double p3 = 1073741824; // Math.Pow(1024,3)
const double p4 = 1099511627776; // Math.Pow(1024,4)
const double t1 = 1000;
const double t2 = 1000000; // Math.Pow(1000,2)
const double t3 = 1000000000; // Math.Pow(1000,3)
const double t4 = 1000000000000; // Math.Pow(1000,4)
const double t5 = 1000000000000000; // Math.Pow(1000,5)
if (size < 0 || size >= t5)
throw new ArgumentOutOfRangeException();
if (size >= 0 && size < t1) {
result = string.Format("{0:G3} B", size);
} else if (size >= t1 && size < p1) {
result = string.Format("{0:G2} KB", size / p1);
} else if (size >= p1 && size < t2) {
result = string.Format("{0:G3} KB", size / p1);
} else if (size >= t2 && size < p2) {
result = string.Format("{0:G2} MB", size / p2);
} else if (size >= p2 && size < t3) {
result = string.Format("{0:G3} MB", size / p2);
} else if (size >= t3 && size < p3) {
result = string.Format("{0:G2} GB", size / p3);
} else if (size >= p3 && size < t4) {
result = string.Format("{0:G3} GB", size / p3);
} else if (size >= t4 && size < p4) {
result = string.Format("{0:G2} TB", size / p4);
} else if (size >= p4 && size < t5) {
result = string.Format("{0:G3} TB", size / p4);
}
return result;
}
public static string ToFriendlyFileSize(this long arg) {
double size = arg;
return size.ToFriendlyFileSize();
}
string result = "N/A";
double size = arg;
const double p1 = 1024;
const double p2 = 1048576; // Math.Pow(1024,2)
const double p3 = 1073741824; // Math.Pow(1024,3)
const double p4 = 1099511627776; // Math.Pow(1024,4)
const double t1 = 1000;
const double t2 = 1000000; // Math.Pow(1000,2)
const double t3 = 1000000000; // Math.Pow(1000,3)
const double t4 = 1000000000000; // Math.Pow(1000,4)
const double t5 = 1000000000000000; // Math.Pow(1000,5)
if (size < 0 || size >= t5)
throw new ArgumentOutOfRangeException();
if (size >= 0 && size < t1) {
result = string.Format("{0:G3} B", size);
} else if (size >= t1 && size < p1) {
result = string.Format("{0:G2} KB", size / p1);
} else if (size >= p1 && size < t2) {
result = string.Format("{0:G3} KB", size / p1);
} else if (size >= t2 && size < p2) {
result = string.Format("{0:G2} MB", size / p2);
} else if (size >= p2 && size < t3) {
result = string.Format("{0:G3} MB", size / p2);
} else if (size >= t3 && size < p3) {
result = string.Format("{0:G2} GB", size / p3);
} else if (size >= p3 && size < t4) {
result = string.Format("{0:G3} GB", size / p3);
} else if (size >= t4 && size < p4) {
result = string.Format("{0:G2} TB", size / p4);
} else if (size >= p4 && size < t5) {
result = string.Format("{0:G3} TB", size / p4);
}
return result;
}
public static string ToFriendlyFileSize(this long arg) {
double size = arg;
return size.ToFriendlyFileSize();
}