Directory.getfiles():文件的特定名称c#

时间:2017-06-14 14:28:30

标签: c#

我一直在努力:

  • 读取特定文件夹中的所有文件;
  • 仅选择以特定模式名称+ .csv
  • 结尾的那些

到目前为止我有什么:

                string[] fileEntriesout = System.IO.Directory.GetFiles(dir + "\\" + "output\\", "*.csv*", System.IO.SearchOption.AllDirectories);

这种方法运行良好,但它获取了所有.CSV文件;

我尝试了什么:

                string[] extensions = { "_fv", "_body", "_out" };
            string[] fileEntriesout = Directory.GetFiles(dir + "\\" + "output\\", "*.csv*", System.IO.SearchOption.AllDirectories).Where(f => extensions.Contains(System.IO.Path.GetFileNameWithoutExtension(f).ToLower())).ToArray();
            string[] fileEntriesout = System.IO.Directory.GetFiles(dir + "\\" + "output\\", "*.*", System.IO.SearchOption.AllDirectories).Where(f => nextensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
            string[] fileEntriesout = System.IO.Directory.GetFiles(dir + "\\" + "output\\", "*.*", System.IO.SearchOption.AllDirectories).Where(f => nextensions.Contains(new FileInfo(f).Name.ToLower())).ToArray();
            string[] fileEntriesout = System.IO.Directory.GetFiles(dir + "\\" + "output\\", "*.*", System.IO.SearchOption.AllDirectories).Where(f => nextensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();

我尝试了我发现的不同想法,但似乎都没有。

总结:

  1. 我需要string []获取包含(通常在文件名末尾)名称的所有.CSV文件:“_ fv”或“_body”或“_out”。
  2. 谢谢。

1 个答案:

答案 0 :(得分:2)

使用LINQEnumerateFiles代替GetFiles + Path.GetFilenameWithoutExtension

string[] extensions = { "_fv", "_body", "_out" };
string[] fileEntriesout = System.IO.Directory.EnumerateFiles(dir + "\\" + "output\\", "*.csv", System.IO.SearchOption.AllDirectories)
    .Where(file => extensions.Any(ex => Path.GetFileNameWithoutExtension(file).EndsWith(ex)))
    .ToArray();
如果你想忽略这个案例(例如,允许StringComparison),

String.EndsWith有一个需要_Body的overoad:

EndsWith(ex, StringComparison.InvariantCultureIgnoreCase)