C#-文件大小转换(字节到GB)
本文关键字:GB 字节 文件大小 转换 C#- | 更新日期: 2024-10-24 12:13:26
我在将字节转换为千兆字节时遇到了一些问题,我有这个代码片段,
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);
}
如有任何帮助/反馈,我们将不胜感激:)
不要将这种格式设置到数据库中。如果只将字节数存储在那里,然后在向用户展示时对其进行格式化,效果会好得多。你会遇到的第一个问题是(例如)在空闲空间上排序时,你可能会得到这样的列表。
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,而不是数字列。