如何使用C#获取包含特定文件的目录列表 [英] How to get list of directories containing particular file using c#

查看:71
本文介绍了如何使用C#获取包含特定文件的目录列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望获得其中包含特定文件的所有文件夹/目录的列表.如何使用C#代码执行此操作.

I wish to get list of all the folders/directories that has a particular file in it. How do I do this using C# code.

例如:考虑我有20个文件夹,其中7个文件夹有一个名为"abc.txt"的文件.我想知道所有包含文件"abc.txt"的文件夹.

Eg: Consider I have 20 folders of which 7 of them have a file named "abc.txt". I wish to know all folders that has the file "abc.txt".

我知道我们可以通过查看路径中的所有文件夹并检查File.Exists(filename);来做到这一点.但我想知道是否还有其他方法可以做到这一点,而不是遍历所有文件夹(在有很多文件夹的情况下,这可能会花费很少的时间).

I know that we can do this by looking thru all the folders in the path and for each check if the File.Exists(filename); But I wish to know if there is any other way of doing the same rather than looping through all the folder (which may me little time consuming in the case when there are many folders).

谢谢
-纳恩(Nayan)

Thanks
-Nayan

推荐答案

我将使用方法

I would use the method EnumerateFiles of the Directory class with a search pattern and the SearchOption to include AllDirectories. This will return all files (full filename including directory) that match the pattern.

使用 Path 类,获取文件目录.

Using the Path class you get the directory of the file.

string rootDirectory = //your root directory;
var foundFiles = Directory.EnumerateFiles(rootDirectory , "abc.txt", SearchOption.AllDirectories);

foreach (var file in foundFiles){
  Console.WriteLine(System.IO.Path.GetDirectoryName(file));
}

EnumerateFiles仅从.NET Framework 4开始可用.如果使用的是.NET Framework的较旧版本,则可以使用

EnumerateFiles is only available since .NET Framework 4. If you are working with an older version of the .NET Framework then you could use GetFiles of the Directory class.

更新(请参阅PLB的评论):

Update (see comment from PLB):

如果拒绝访问目录,则上面的代码将失败.在这种情况下,您需要一个接一个地搜索每个目录以处理异常.

The code above will fail if the access to a directory in denied. In this case you will need to search each directory one after one to handle exceptions.

public static void SearchFilesRecursivAndPrintOut(string root, string pattern)
{
    //Console.WriteLine(root);
    try
    {
        var childDireactory = Directory.EnumerateDirectories(root);
        var files = Directory.EnumerateFiles(root, pattern);

        foreach (var file in files)
        {
            Console.WriteLine(System.IO.Path.GetDirectoryName(file));
        }

        foreach (var dir in childDireactory)
        {
            SearchRecursiv(dir, pattern);
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception);
    }
}

这篇关于如何使用C#获取包含特定文件的目录列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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