开发者

finding files inside nested folder [closed]

Closed. This question needs to be more focused. It is not currently accepting answers. 开发者_StackOverflow

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 8 years ago.

Improve this question

How to search for files inside nested folders?


have a look at this function

System.IO.DirectoryInfo.GetFiles("SearchPattern",SearchOption.AllDirectories)

http://msdn.microsoft.com/en-us/library/ms143327.aspx


You need to do it in recursively. Follow the link below for code sample.

http://support.microsoft.com/kb/303974


Use recursion.

Write a method that searches the file in a specific folder. Call the method from within itself for each subdirectory and let it return the path if it found the file.

Pseudo-C#-Code(Only for getting the idea) :

public string SearchFile (string path, string filename)
{
    if (File.exists(path+filename)) return path;

    foreach(subdir in path)
    {
        string dir = Searchfile(subdirpath,filename);
        if (dir != "") return dir;
    }
}

This will run through all subdirectories and return the path to the searched file, if it is in there, else an empty string.


try this:

static string SearchFile(string folderPath, string fileToSearch)
{
    string foundFilePath = null;
    ///Get all directories in current directory
    string[] directories = Directory.GetDirectories(folderPath);

    if (directories != null && directories.Length > 0)
    {
        foreach (string dirPath in directories)
        {
            foundFilePath = SearchFile(dirPath, fileToSearch);
            if (foundFilePath != null)
            {
                return foundFilePath;
            }
        }                
    }

    string[] files = Directory.GetFiles(folderPath);
    if (files != null && files.Length > 0)
    {
        foundFilePath = files.FirstOrDefault(filePath => Path.GetFileName(filePath).Equals(fileToSearch, StringComparison.OrdinalIgnoreCase));                
    }

    return foundFilePath;
}


try searching for fluent path in codeplex...it give shortcuts to serach for files within directories using lambdas/linq


Have a look at the DirectoryInfo class.

You will probably need a bit of recursion going on


With Linq and Directory.EnumerateFiles

var files =
    from file in Directory.EnumerateFiles(rootFolder,searchFor,SearchOption.AllDirectories)
    select file;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜