How to get file size in C#?

WBOY
Release: 2023-09-08 14:29:02
forward
1921 people have browsed it

How to get file size in C#?

FileInfo class is used to handle files and their operations in C#.

It provides properties and methods for creating, deleting and reading files. it uses The StreamWriter class writes data to a file. It is part of the System.IO namespace.

The Directory property retrieves an object representing the file's parent directory.

The DirectoryName property retrieves the full path of the parent directory

The Exists property checks whether a file exists before operating on it.

The IsReadOnly property retrieves or sets a value that specifies whether the file can be read. Revise.

Length retrieves the size of the file.

Name retrieves the name of the 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);
   }
}
Copy after login

Output

12
Copy after login

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);
   }
}
Copy after login

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.
Copy after login

The above is the detailed content of How to get file size in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template