C# 如何从指定的文件夹中获取文件信息?
我有一个包含多个文件夹的路径。每个文件夹都有多个子文件夹,每个主文件夹中的一个子文件夹名为C# 如何从指定的文件夹中获取文件信息?,c#,C#,我有一个包含多个文件夹的路径。每个文件夹都有多个子文件夹,每个主文件夹中的一个子文件夹名为prog,其中包含一个xml文件。现在,其他子文件夹中可能也有xml文件,但我只想获取每个主文件夹中prog子文件夹中xml文件的文件信息 如果我这样做 DirectoryInfo myDir = new DirectoryInfo(@"E:\\Testing"); foreach (FileInfo xmlFile in myDir.EnumerateFiles("*.xml", SearchOptio
prog
,其中包含一个xml文件。现在,其他子文件夹中可能也有xml文件,但我只想获取每个主文件夹中prog
子文件夹中xml文件的文件信息
如果我这样做
DirectoryInfo myDir = new DirectoryInfo(@"E:\\Testing");
foreach (FileInfo xmlFile in myDir.EnumerateFiles("*.xml", SearchOption.AllDirectories))
{
string myDirectoryName = Path.GetFileNameWithoutExtension(xmlFile.Name);
//Do some stuff
}
然后我从每个主文件夹的所有子文件夹中获取所有xml文件,但我只希望xml文件位于prog
子文件夹中
如何实现这一点?这将使您在prog文件夹中获得所有.xml文件。这假设不区分大小写,但可以调整
DirectoryInfo myDir = new DirectoryInfo(@"E:\\Testing");
foreach(FileInfo myFile in myDir.EnumerateFiles(@"*.xml", SearchOption.AllDirectories)
.Where(fi => fi.Directory.Name.Equals("prog")))
{
// Do something with .xml files in "prog" folder
}
不要递归枚举每个XML文件,而是枚举myDir的所有目录,在每个目录的路径中添加“prog”,然后枚举这些目录中的所有XML文件:
var progXmlFiles = myDir.EnumerateDirectories()
.Select(d => Path.Combine(d.FullName, "prog"))
.SelectMany(d => new DirectoryInfo(d).EnumerateFiles("*.xml"));
您说过在每个主文件夹和xml文件中都会有一个\prog子文件夹。但是后来您说您只想获取xml文件的文件信息(复数)
获取prog目录中所有xml文件的一种方法是在for循环的开头添加以下内容:
if (-1 == xmlFile.FullName.IndexOf("\\prog\\"))
continue;
如果只希望.xml文件立即位于prog文件夹中,请使用以下方法:
if (-1 == xmlFile.FullName.IndexOf("\\prog\\" + xmlFile.Name))
continue;
以下是输出:
Finding all XML files under C:\Testing
a_test C:\Testing\a\prog\a_test.xml
b_test C:\Testing\b\prog\b_test.xml
d_test C:\Testing\d\prog\d_test.xml
Done...
Finished, press any key...
这是我设置的测试目录和测试文件:
C:.
├───a
│ ├───a_subdir \ a_test_error.xml
│ ├───a_subdir2
│ └───prog \ a_test.xml
├───b
│ ├───b_subdir
│ └───prog \ b_test.xml
├───c
│ └───prog
├───d
│ ├───d_subdir \ d_test_error.xml
│ └───prog \ d_test.xml
└───e
如何删除此
目录中的区分大小写。Name.ToLower.Equals
不适用于fi.Directory.Name.Equals(“prog”,StringComparison.OrdinalIgnoreCase)