【问题标题】:How can i get ALL File Extentions in C#? [closed]如何在 C# 中获取所有文件扩展名? [关闭]
【发布时间】:2017-03-04 07:05:31
【问题描述】:
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 exstention是否存在?

【问题讨论】:

  • 不,文件可以有任意扩展名或根本没有。有一个“注册”扩展的概念,但是你不需要注册一个文件扩展来使用它。
  • 你想达到什么目的?您认为哪些扩展有效?你的问题很不清楚。

标签: c# directory


【解决方案1】:

一个文件可以有任何它想要的扩展名。它可以是任意长度的任意字符序列。由于该序列是无限的,因此无法将它们全部放在一个列表中。

如果您想知道您感兴趣的目录是否有任何具有给定扩展名的文件,您可以枚举目录中的所有文件并将其所有扩展名放入一个集合中。

【讨论】:

    【解决方案2】:

    你可以用 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!!");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2023-04-06
      • 2013-11-03
      相关资源
      最近更新 更多