如何在 C# 中获取文件大小?

csharpserver side programmingprogramming

FileInfo 类用于在 C# 中处理文件及其操作。

它提供用于创建、删除和读取文件的属性和方法。它使用 StreamWriter 类将数据写入文件。它是 System.IO 命名空间的一部分。

Directory 属性检索表示文件父目录的对象。

DirectoryName 属性检索文件父目录的完整路径。

Exists 属性在操作文件之前检查文件是否存在。

IsReadOnly 属性检索或设置指定文件是否可以修改的值。

Length 检索文件的大小。

Name 检索文件的名称。

示例

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);
   }
}

输出

12

示例

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);
   }
}

输出

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.

相关文章