string path = "C:\\BSD";
string extension = Console.ReadLine();
List<string> allExstensions = getAllExtention(); // Is there a method where I get all File Extensions : *.png, *.txt,.......
if (!allExstensions.Contains(extension))
throw new Exception("The Extension you wrote does not exist!!");
foreach (string directory in Directory.GetDirectories(path))
{
foreach (string file in Directory.GetFiles(directory,extension))
{
Console.WriteLine(file);
}
}
有没有办法检查是否存在enterf exsits?
答案 0 :(得分:3)
文件可以包含任何所需的扩展名。它可以是任何长度的任何字符序列。由于该序列是无限的,因此无法将它们全部放入列表中。
如果您想知道您感兴趣的目录是否包含任何具有给定扩展名的文件,您可以枚举目录中的所有文件并将其所有扩展名放入一个集合中。
答案 1 :(得分:0)
您可以使用Linq尝试此操作:
string path = "C:\\BSD";
string extension = Console.ReadLine();
int count = 0;
foreach (string file in Directory.GetFiles(path, "*.*",SearchOption.AllDirectories).Where(x => x.EndsWith(extension)))
{
Console.WriteLine(file);
count++;
}
if (count == 0)
throw new Exception("The Extension you wrote does not exist!!");