要从目录中文件列表中搜索文件,请尝试运行以下代码-
using System; using System.IO; namespace Demo { class Program { static void Main(string[] args) { //创建一个DirectoryInfo对象 DirectoryInfo mydir = new DirectoryInfo(@"d:\amit"); //获取目录中的文件,它们的名称和大小 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