2012-08-07 269 views
0

我有一些问题与字节转换为千兆字节, 我有这样的代码片段,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); 

     } 

任何帮助/反馈将不胜感激:)

+0

仍然不清楚,你在第二代码中的位置和目的是什么。请提供更多细节。 – 2012-08-07 10:34:52

+0

你的意思是像'driveList [i] .TotalSize'这样传递给你的'FormatBytes'方法(它返回字符串并且不会像预期的那样长)? – V4Vendetta 2012-08-07 10:38:54

+0

如果你想使用scale 1024的使用(kibibyte,mebibyte和gibibyte - KiB,MiB和GiB),否则如果你有scale 1000,你应该使用kB而不是KB。 http://en.wikipedia.org/wiki/Kibibyte – 2012-08-07 10:53:36

回答

3

不要把那种格式化成你的数据库中。如果您只将字节数存储在那里,然后在将其呈现给用户时进行格式化,则会好很多。你遇到的第一个问题是在空闲空间排序时(例如),那么你可能会得到这样的列表。

Drive  Free Space 
C   12 GB 
E   13 Bytes 
D   16 MB 

因此,最好将实际金额存储在那里,以便您可以正确处理数据。无论如何,如果你坚持并想要存储这个,那么你只需像这样添加它。

serverDrives.DriveLetter = driveList[i].Name; 
serverDrives.TotalSpace = FormatBytes(driveList[i].TotalSize); 
serverDrives.DriveLabel = driveList[i].VolumeLabel; 
serverDrives.FreeSpace = FormatBytes(driveList[i].TotalFreeSpace); 
serverDrives.DriveType = driveList[i].DriveFormat; 

请记住,这将要求您的TotalSpace和FreeSpace列是数据库中的字符串/ varchar,而不是数字。

+0

你想用你的代码实现上述目的吗? – 2012-08-07 10:41:58

+0

好吧,好吧,我现在只是把它保留在字节上,因为它是一个更准确一点,不会搞砸 谢谢:) – Ghostyy 2012-08-07 10:46:02