2012-08-07 271 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