KnowDotNet Visual Organizer

Exploring System.IO

Convert Byte Size of File to Meaningful Information

by Willliam Ryan
Print this Article Discuss in Forums

One of the really impressive libraries is system.IO.  This namespace has many powerful classes and allows you to do some really formerly difficult things with little to no effort.  In this article, I'm going to show you how to use the FileInfo and some basic string.Format manipulation to return the size of a file in a clearly formatted fashion.

One of the constructors of the FileInfo class allows you to pass in a string which is the name of the file (ie @"C:\someFile.txt").  As such, you declare it like this:

FileInfo f = new FileInfo(@"C:\someFile.txt");


In case you weren't aware, the "\" character is a special character in C#, so you can either use two of them where you normally use one "\\" or you can use C#'s escapte symbol "@")  

Now, here is the method I created which takes a FileInfo Object, interrogates its .Length property and then does its thing.  It's pretty straightforward so let me just show the code.

public string ShowSize(FileInfo myFile)
{
       long NumberOfBytes = myFile.Length;
       if(NumberOfBytes >=1073741824)
       {
return string.Format("{0:#0.00}",NumberOfBytes/1024, 1024, 1024 + " gb");}
        else if(NumberOfBytes >=1048576)
       {
return string.Format("{0:#0.00}", NumberOfBytes/1024/1024 + " mb");}
         else if(NumberOfBytes >=1024)
       {
return string.Format("{0:#0.00}", NumberOfBytes/1024 + "kb"); }
        else if(NumberOfBytes > 0 && NumberOfBytes < 1024)<BR>       {return string.Format("{0:#0.00}", NumberOfBytes + " bytes"); }
      else{return "0 bytes";}
}

Then for the call:

       private void button1_Click(object sender, System.EventArgs e)
       {FileInfo f =
new FileInfo(@"C:\LABS.xml");
        MessageBox.Show(ShowSize(f));}



I would really encourage you to look into the IO Library, particularly the Directory, DirectoryInfo and the Path Classes...  or stop back soon and I'll have a few articles on it.

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing