Search code examples
c#asp.net-core.net-core.net-standard

.NET Core : IFileProvider.GetDirectoryContents recursive not working


I would like to scan a directory ("C:/test") and get all files .pdf recursively I create a provider like this :

IFileProvider provider = new PhysicalFileProvider("C:/test"); // using config in my code and also tried with "C:/test/"

I placed some pdf in directories and subdirectories

There's a file with this path : C:/test/pdf59.pdf Another with C:/test/testComplexe/pdf59.pdf

Where I try these lines, they all return "NotFoundDirectoryException" :

provider.getDirectoryContents(@"**")
provider.getDirectoryContents(@"*")
provider.getDirectoryContents(@"*.*")
provider.getDirectoryContents(@"**.*")    
provider.getDirectoryContents(@"pdf59.pdf")
provider.getDirectoryContents(@"*.pdf")

Exception this line :

provider.getDirectoryContents(@"testComplexe")

How could i query these recursive directories and files ? Thank you


Solution

  • You can write your own recursive function.

    var files = new List<IFileInfo>();
    GetFiles("C:/Tests", files);
    
    private void GetFiles(string path, ICollection<IFileInfo> files)
    {
        IFileProvider provider = new PhysicalFileProvider(path);
    
        var contents = provider.GetDirectoryContents("");
    
        foreach (var content in contents)
        {
            if (!content.IsDirectory && content.Name.ToLower().EndsWith(".pdf"))
            {
                files.Add(content);
            }
            else
            {
                GetFiles(content.PhysicalPath, files);
            }
        }
    }