试题要求:
如何搜索指定目录下的所有文本文件
考察知识点:
DirectoryInfo或Directory
参考答案1:
private static void SearchTxtFileFromDirectory(string dir)
{
if (Directory.Exists(dir))
{
DirectoryInfo directoryInfo = new DirectoryInfo(dir);
FileInfo[] allTxtFiles = directoryInfo.GetFiles("*.txt",SearchOption.AllDirectories);
foreach (FileInfo fileInfo in allTxtFiles)
{
Console.WriteLine(fileInfo.FullName);
}
}
}
参考答案2:
/// <summary>
/// 递归搜索指定目录(包括子目录)下的所有文本文件
/// </summary>
/// <param name="directory"></param>
private static void GetTxtFileFromDirectory(string directory)
{
if (Directory.Exists(directory))
{
try
{
DirectoryInfo directoryInfo = new DirectoryInfo(directory);
FileInfo[] allTxtFile = directoryInfo.GetFiles("*.txt", SearchOption.TopDirectoryOnly);
foreach (FileInfo fileInfo in allTxtFile)
{
Console.WriteLine(fileInfo.FullName);
}
DirectoryInfo[] allChildrenDirectory = directoryInfo.GetDirectories();
foreach (DirectoryInfo item in allChildrenDirectory)
{
GetTxtFileFromDirectory(item.FullName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
else
{
Console.WriteLine("该目录不存在");
}
}