TechBubbles

Calculating the size of the File in C#

Introduction

This code snippet explains how to calculate the size of the file and display in a label control. For example I am taking PDF file to find the size. It Displays the size of the file in Bytes, Kilobytes and Megabytes.

 

//Calculate size of the PDF file
       if (PdfFilePath.EndsWith("pdf"))
       {
           FileInfo info = new FileInfo(PdfFilePath);
           long fileSize = info.Length;
           string strFileSize = FormatFileSize(fileSize);
           lblFileSize.Text = strFileSize;
        }

Assume that PdfFilePath contains the path of the file which we are calculating the size.

private string FormatFileSize(long bytes)
   {
       if (bytes > terabyte)
       {
           return ((float)bytes / (float)terabyte).ToString("0.00 TB");
       }
       else if (bytes > gigabyte)
       {
           return ((float)bytes / (float)gigabyte).ToString("0.00 GB");
       }
       else if (bytes > megabyte)
       {
           return (((float)bytes / (float)megabyte)).ToString("0.00 MB");
       }
       else if (bytes > kilobyte)
       {
           return ((float)bytes / (float)kilobyte).ToString("0.00 KB");
       }
       else return bytes + " Bytes";
   }

3 Comments so far

  1. DotNetKicks.com October 14th, 2008 10:53 am

    Calculating the size of the File in C# …

    You’ve been kicked (a good thing) - Trackback from DotNetKicks.com…

  2. Mads Kristensen October 14th, 2008 4:56 pm

    Great code. Have you considered to let the user of this method define his own formatting? Your code only works in England and USA where you use a dot (.) as a separator. Most other countries use a comma (,).

  3. Kalyan Bandarupalli October 14th, 2008 6:50 pm

    Thanks for the notice. i will update the method as generic
    one with a parameter where user can supply the separator.

Leave a reply