Để tìm kiếm tệp từ danh sách tệp trong thư mục, hãy thử chạy mã sau -
Ví dụ
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();
}
}
} Ở trên, trước tiên chúng tôi đã thêm thư mục mà chúng tôi muốn tìm tệp -
DirectoryInfo mydir = new DirectoryInfo(@"d:\amit");
Sau đó, đọc tệp -
FileInfo [] f = mydir.GetFiles();
foreach (FileInfo file in f) {
C onsole.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length);
} Sau đây là kết quả -
FileName: Info.txt: Size: 2kb File Name: New.html: Size: 10kb