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";
   }


4 responses to “Calculating the size of the File in C#”

  1. Calculating the size of the File in C# …

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

  2. Mads Kristensen Avatar

    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 Avatar
    Kalyan Bandarupalli

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

  4. Frank-Ove Avatar

    Hi,

    Just want to comment that you also can achieve the same using the built-in methods in the Microsoft.SharePoint.Utilities namespace, namely the SPUtility class:

    string fileSize = SPUtility.FormatSize(fileSize);

    Frank 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *