April 18, 2010

Determining File Size - C#

In a previous post, I detailed how simple it was to list the files in a directory and access other file information. One piece of information that is not directly apparent in the FileInfo Object is file size. I was initially looking for a size attribute, but file size is handled by the length attribute. So calling .Length on a FileInfo object will return the size of the file in bytes.

Dividing that length by a power of two will give the file size in a appropriate format. The example below is the listing of the sizes of files in a directory in gigabytes.
DirectoryInfo directory = new DirectoryInfo("F:/Media/Movies");
FileInfo[] files = directory.GetFiles();
foreach (FileInfo onefile in files){
Console.WriteLine(onefile.Name + ", length: " +
Math.Round((onefile.Length / 1073741824f),3) + " GB");
}
onefile.Length returns the size of the file in bytes, so dividing by 1073741824 will give the size of the file in gigabytes. Wrapping the division in Math.Round truncates the length to 3 decimal places.

I used this quick table to lookup the powers of two factors for Kilobytes (1024), Megabytes (1,048,576), Gigabytes (1,073,741,824) and Terabytes(1,099,511,627,776.)

Original size conversion found here - http://dotnetperls.com/convert-bytes-megabytes

2 comments:

  1. So I don't use VB, but I might start. They have code snippets for stuff exactly like this. Simply use Ctrl-K, Ctrl-X to bring up the snippets intellisense or use the Code Snippets Manager (Ctrl-K, Ctrl-B) under the Tools menu.

    They have everything from file I/O to LINQ queries to sound. Awesome!

    ReplyDelete
  2. I took a look at VB snippets and now know why people use Visual Basic. Those were very, very impressive.

    ReplyDelete