Get File Size in C#

This tutorial will discuss the method for calculating the file size of a file in C#.

Get File Size With the FileInfo.Length Property in C

The FileInfo class provides methods for creating, opening, copying, deleting, and moving files in C#. The FileInfo.Length property gets the size of a file in bytes. We have first to initialize an object of the FileInfo class and pass the path to the file as the constructor’s argument. The following code example shows us how we can get a file’s file size with the FileInfo.Length property in C#.

using System;
using System.IO;

namespace file_size
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo fileinfo = new FileInfo("dark.jpg");
            Console.WriteLine(fileinfo.Length);
        }
    }
}

Output:

246804

In the above code, we initialized the instance fileinfo of the FileInfo class and passed the path dark.jpg in the constructor. We then printed the file size of the dark.jpg file with the fileinfo.Length property in C#. The output here shows that the size of the file dark.jpg is 246804 bytes.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp File

  • Check Whether a File Exists in C#
  • Download a File From a URL in C#