如何从给定路径中的特定结构文件夹中获取文件? [英] How do I get files from a specificly structured folder in a given path?

查看:92
本文介绍了如何从给定路径中的特定结构文件夹中获取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件夹,其中有结构中的其他子文件夹

2017-12456-12463-1023\2017\12456\12463\ 1023 \abc.txt

2016-32456-15463-2033\2016\32456\15463\2033\xyz。 txt

......等等...

现在,还有其他每个文件夹中的子文件夹

2017-12456-12463-1023

2016-32456-15463-2033

包含 txt 文件

我如何只获得在上面提到的文件夹结构中文件夹 1023 2033 中的文件

在VB中我使用了类似
的内容


我的尝试:



I have a folder inside which there are other sub-folders in the structure
2017-12456-12463-1023\2017\12456\12463\1023\abc.txt
2016-32456-15463-2033\2016\32456\15463\2033\xyz.txt
... so on ...
Now, there are other sub-folders inside each of the folders
2017-12456-12463-1023
2016-32456-15463-2033
which contains txt files
How do I get only the txt files from folders 1023, 2033 in the above mentioned folder structures.
In VB I used something like

What I have tried:

Dim txtFiles = Directory.EnumerateFiles(targetDirectory, "*.txt", SearchOption.AllDirectories).Where(Function(f) f Like "*\#*\#*\#*\#*.txt").ToArray





但是如何在c#中执行?



But how do I do it in c#?

推荐答案

VB.NET和C#使用所有相同的类,因此它应该完全相同。您可以从 Directory.EnumerateFiles Method( System.IO) [ ^ ]。
VB.NET and C# use all the same classes so it should be exactly the same. You can check it out from Directory.EnumerateFiles Method (System.IO)[^].


对于迟到的解决方案感到抱歉,但今天我用自己的东西一直很忙。

您可以尝试:

Sorry for the late solution but I've been quite busy today with my own stuff.
You can try:
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

// ...

// First retrieve all files in the hierarchy
IEnumerable<string> allFiles = Directory.EnumerateFiles(targetDirectory, "*.txt", SearchOptions.AllDirectories);

// Then isolate only those which are in the directory you are interested in
Regex r = new Regex(@".+\\[\d]+\\[\d]+\\[\d]+\\[\d]+\\[^\\]+\.txt", RegexOptions.Compiled | RegexOptions.IgnoreCase);
string[] files = allFiles.Where(f => r.IsMatch(f)).ToArray();



正则表达式是一个快速构建的,但我使用了 Expresso [ ^ ]进行测试,看起来是正确的。



希望这会有所帮助。亲切。



:更正了我使用Match方法而不是正确的IsMatch方法的错误。






The regex is a quick-built, but I used Expresso[^] to test it and it seems correct.

Hope this helps. Kindly.

: Corrected a mistake where I used the Match method instead of the proper IsMatch method.

:

using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

class YourClass
{
   private static readonly Regex regex = new Regex(@".+\\[\d]+\\[\d]+\\[\d]+\\[\d]+\\[^\\]+\.txt", RegexOptions.Compiled | RegexOptions.IgnoreCase);

   // ...

   // In your method:
   string[] files = Directory.EnumerateFiles(targetDirectory, "*.txt", SearchOptions.AllDirectories).Where(f => regex.IsMatch(f)).ToArray();
}


这篇关于如何从给定路径中的特定结构文件夹中获取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆