TechBubbles Microsoft Technology BLOG

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

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.

4 Comments

  • 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 (,).

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

  • 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 🙂

TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud