[英]Measuring fileinfo.Length objects into kbs
我有以下代碼:
foreach (string p in dirs)
{
string path = p;
string lastAccessTime = File.GetLastAccessTime(path).ToString();
bool DirFile = File.Exists(path);
FileInfo fInf = new FileInfo(path);
DateTime lastWriteTime = File.GetLastWriteTime(p);
dirFiles.Add(p + "|" + lastAccessTime.ToString() + "|" + DirFile.ToString() + "|" + lastWriteTime.ToString() + "|" + fInf.Length.ToString());
}
我有一個 fInf.Length.ToString(),我想用 kbs 來衡量輸出。 關於如何做到這一點的任何想法? 例如,我不想獲得 2048 作為文件大小,而是只想獲得 2Kb。
預先感謝您的幫助
以下是如何將其分解為千兆字節、兆字節或千字節:
string sLen = fInf.Length.ToString();
if (fInf.Length >= (1 << 30))
sLen = string.Format("{0}Gb", fInf.Length >> 30);
else
if (fInf.Length >= (1 << 20))
sLen = string.Format("{0}Mb", fInf.Length >> 20);
else
if (fInf.Length >= (1 << 10))
sLen = string.Format("{0}Kb", fInf.Length >> 10);
sLen
會給你答案。 您可以將它包裝在一個函數中,然后只傳入Length
,甚至是FileInfo
對象。
如果您想要 1000 字節而不是“真實”千字節,則可以分別用1000
和/1000
替換1 << 10
和>> 10
,對於其他使用 1000000 和 1000000000 的類似。
如果您希望長度為(長)整數:
long lengthInK = fInf.Length / 1024;
string forDisplay = lengthInK.ToString("N0") + " KB"; // eg, "48,393 KB"
如果要將長度作為浮點數:
float lengthInK = fInf.Length / 1024f;
string forDisplay = lengthInK.ToString("N2") + " KB"; // eg, "48,393.68 KB"
試試下面的行:
string sizeInKb = string.Format("{0} kb", fileInfo.Length / 1024);
重構@lavinio 的回答:
public static string ToFileLengthRepresentation(this long fileLength)
{
if (fileLength >= 1 << 30)
return $"{fileLength >> 30}Gb";
if (fileLength >= 1 << 20)
return $"{fileLength >> 20}Mb";
if (fileLength >= 1 << 10)
return $"{fileLength >> 10}Kb";
return $"{fileLength}B";
}
[TestFixture]
public class NumberExtensionsTests
{
[Test]
[TestCase(1024, "1Kb")]
[TestCase(2048, "2Kb")]
[TestCase(2100, "2Kb")]
[TestCase(700, "700B")]
[TestCase(1073741824, "1Gb")]
public void ToFileLengthRepresentation(long amount, string expected)
{
amount.ToFileLengthRepresentation().ShouldBe(expected);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.