搜索嵌套文件

时间:2010-05-14 11:40:43

标签: asp.net

如何在嵌套文件夹中搜索文件?

3 个答案:

答案 0 :(得分:0)

这是你在C#中的表现: http://support.microsoft.com/kb/303974

关键是递归。您的方法必须为它找到的每个文件夹调用自己。因此它会越来越深入调用堆栈,但只调用自身。例如,假设您有一个文件夹a,其中包含文件夹aaab。这些文件夹中包含文件夹aaaaba。然后,您将首先遍历a的所有内容,即aaab。然后,您将调用相同的方法并对它们执行相同的操作,直到没有其他文件夹为止。

答案 1 :(得分:0)

我认为你可以使用

 DirectoryInfo di = new DirectoryInfo(path);
 FileInfo[] files = di.GetFiles(searchPattern, SearchOption.AllDirectories);

如MSDN中SearchOption.AllDirectories

所述
Includes the current directory and all the subdirectories in a search operation. This option includes reparse points like mounted drives and symbolic links in the search.

答案 2 :(得分:0)

尝试像这样的递归方法....

    public string SearchForFile(string directory, string filename)
    {
        string file = "";

        //Look in this directory first
        string[] files = Directory.GetFiles(directory, filename);
        if (files.Count() > 0)
            file = files[0];
        else  //Not found here, so try the sub-directories
        {
            foreach (string subDirectory in Directory.GetDirectories(directory))
            {
                file = SearchForFile(subDirectory, filename);
                if (file != "")
                    break;
            }
        }

        return file;
    }