如何在 C# 中獲取檔案大小?
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.
廣告