我有一些问题与字节转换为千兆字节, 我有这样的代码片段,C# - 文件大小转换(字节到GB)
public static string FormatBytes(long bytes)
{
const int scale = 1024;
string[] orders = new string[] { "GB", "MB", "KB", "Bytes" };
long max = (long)Math.Pow(scale, orders.Length - 1);
foreach (string order in orders)
{
if (bytes > max)
{
return string.Format("{0:##.##} {1}", Decimal.Divide(bytes, max), order);
}
max /= scale;
}
return "0 Bytes";
}
打印尺寸的控制台应用程序时,这工作完全正常。 但是 我不知道如何将它实现到我的代码的这个(下面)部分,以便它在将它们插入到我的SQL表中时转换文件大小。
List<DriveInfo> driveList = DriveInfo.GetDrives().Where(x=>x.IsReady).ToList<DriveInfo>();
//Insert information of one server - You will need get information of all servers
server.ServerID = 0; //Here is necessery put PK key. I recommend doing the SQL server will automatically generate the PK.
server.ServerName = string.Concat("Server ", driveList.Count);
//Inserts information in the newServers object
for (int i = 0; i < driveList.Count; i++)
{
ServerDrive serverDrives = new ServerDrive();
//Put here all the information to obeject Server
serverDrives.DriveLetter = driveList[i].Name;
serverDrives.TotalSpace = driveList[i].TotalSize;
serverDrives.DriveLabel = driveList[i].VolumeLabel;
serverDrives.FreeSpace = driveList[i].TotalFreeSpace;
serverDrives.DriveType = driveList[i].DriveFormat;
// server.ListServerDrives.Add(serverDrives);
server.ServerDrives.Add(serverDrives);
}
任何帮助/反馈将不胜感激:)
仍然不清楚,你在第二代码中的位置和目的是什么。请提供更多细节。 – 2012-08-07 10:34:52
你的意思是像'driveList [i] .TotalSize'这样传递给你的'FormatBytes'方法(它返回字符串并且不会像预期的那样长)? – V4Vendetta 2012-08-07 10:38:54
如果你想使用scale 1024的使用(kibibyte,mebibyte和gibibyte - KiB,MiB和GiB),否则如果你有scale 1000,你应该使用kB而不是KB。 http://en.wikipedia.org/wiki/Kibibyte – 2012-08-07 10:53:36