Reputation: 77
I am having some problems with converting bytes to gigabytes, I have this code snippet,
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";
}
which works perfectly fine when printing the sizes to the Console App. BUT I don't know how to implement it into this(below) part of my code so that it will convert the file sizes when they are inserted into my SQL Table.
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);
}
Any help/feedback would be greatly appreciated :)
Upvotes: 0
Views: 2715
Reputation: 17532
Don't put that kind of formatting into your database. It's a lot better if you just store the number of bytes there and then format it when you present it to the user. The first problem you will run into is when sorting on free space (for example), then you might get a list such as this.
Drive Free Space
C 12 GB
E 13 Bytes
D 16 MB
So it's better to store the actual amounts there so you can properly work with your data. Anyhow, if you persist and want to store this, then you simply add it like this.
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;
Just remember that this will require that your TotalSpace and FreeSpace columns are strings/varchar in your database and not numerical.
Upvotes: 3