使用 C# 进行文件搜索
要從目錄中的檔案清單中搜尋檔案,請嘗試執行以下程式碼 −
範例
using System; using System.IO; namespace Demo { class Program { static void Main(string[] args) { //creating a DirectoryInfo object DirectoryInfo mydir = new DirectoryInfo(@"d:\amit"); // getting the files in the directory, their names and size FileInfo [] f = mydir.GetFiles(); foreach (FileInfo file in f) { Console.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length); } Console.ReadKey(); } } }
上面,我們首先新增目錄,我們想要在其中尋找檔案 −
DirectoryInfo mydir = new DirectoryInfo(@"d:\amit");
然後讀取檔案 −
FileInfo [] f = mydir.GetFiles(); foreach (FileInfo file in f) { C onsole.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length); }
以下是輸出 −
FileName: Info.txt: Size: 2kb File Name: New.html: Size: 10kb
广告