How do you get the file size in C#?


The FileInfo class is used to deal with file and its operations in C#.

It provides properties and methods that are used to create, delete and read file. It uses StreamWriter class to write data to the file. It is a part of System.IO namespace.

The Directory property retrieves an object that represents the parent directory of a file.

The DirectoryName property retrieves the full path of the parent directory of a file.

The Exists property checks for the presence of a file before operating on it.

The IsReadOnly property retrieves or sets a value that specifies whether a file can be modified.

The Length retrieves the size of a file.

The Name retrieves the name of a file.

Example

class Program{
   public static void Main(){
      var path = @"C:\Users\Koushik\Desktop\Questions\ConsoleApp\Data.csv";
      long length = new System.IO.FileInfo(path).Length;
      System.Console.WriteLine(length);
   }
}

Output

12

Example

class Program{
   public static void Main(){
      var path = @"C:\Users\Koushik\Desktop\Questions\ConsoleApp";
      DirectoryInfo di = new DirectoryInfo(path);
      FileInfo[] fiArr = di.GetFiles();
      Console.WriteLine("The directory {0} contains the following files:", di.Name);
      foreach (FileInfo f in fiArr)
         Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length);
   }
}

Output

The directory ConsoleApp contains the following files:
The size of ConsoleApp.csproj is 333 bytes.
The size of Data.csv is 12 bytes.
The size of Program.cs is 788 bytes.

Updated on: 25-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements