Question

I'm using this method:

public static long GetFileSizeOnDisk(string file)
        {
            FileInfo info = new FileInfo(file);
            uint dummy, sectorsPerCluster, bytesPerSector;
            int result = GetDiskFreeSpaceW(info.Directory.Root.FullName, out sectorsPerCluster, out bytesPerSector, out dummy, out dummy);
            if (result == 0) throw new Win32Exception();
            uint clusterSize = sectorsPerCluster * bytesPerSector;
            uint hosize;
            uint losize = GetCompressedFileSizeW(file, out hosize);
            long size;
            size = (long)hosize << 32 | losize;
            return ((size + clusterSize - 1) / clusterSize) * clusterSize;
        }

And use it like this:

label10.Text = GetFileSizeOnDisk(previewFileName).ToString();

The result for example is: 5074944 But what i want it to dispaly is if it's low then mega byte then display as kb and if above then as mb or gigabyte i mean if 5074944 is megabyte then display it for example as: 5,074944 MB Including the MB

Or how it known to display/write sizes.

Was it helpful?

Solution

The nice thing about programming is, that repetative tasks can be automated. A solution that automatically calculates the size could be:

  • find file size
  • repeat until size is bigger than 1024
  • divide size by 1024
  • store size position
  • loop

The code can look like this:

private String sizeFormatter(Int64 filesize)
{
    var sizes = new List<String> { "B", "KB", "MB", "GB", "TB", "PB" };
    var size = 0;
    while (filesize > 1024)
    {
        filesize /= 1024;
        size++;
    }
    return String.Format("{0}{1}", filesize, sizes[size]);
}

And the usage:

var bigFile = new FileInfo("C:\\oracle\\OracleXE112_Win32.zip");
var smallFile = new FileInfo("C:\\oracle\\ScriptCreateUser.sql");
var verySmallFile = new FileInfo("C:\\ScriptCreateTable.sql");
Console.WriteLine(sizeFormatter(bigFile.Length));
Console.WriteLine(sizeFormatter(smallFile.Length));
Console.WriteLine(sizeFormatter(verySmallFile.Length));

The output is:

312MB
12KB
363B

This method could be optimized regarding accuracy, but for the general usage it should be alright.

OTHER TIPS

You should just use some if statements:

long size = GetFileSizeOnDisk(previewFileName);

if(size > 1024 * 1024 * 1024)
{
    label10.Text = (size / 1024 * 1024 * 1024F).ToString() + " Gb";
}
else if(size > 1024 * 1024)
{
    label10.Text = (size / 1024 * 1024F).ToString() + " Mb";
}
else if(size > 1024)
{
    label10.Text = (size / 1024F).ToString() + " Kb";
}
else
{
    label10.Text = size.ToString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top