asp.net core fileprovider get all drives

Viewed 1971

I would like to get all drives with the IFileProvider (PhysicalFileProvider) in asp.net core 2.0.

Is there a extra using which have to get? Or has anybody an example for this?

regards Chris

2 Answers

IFileProvider assumes you start from a single root and as far as I know .Net core does not provide a direct way to group all drives under a single root directory.

PhysicalFileProvider by itself certainly won't work for the same reason.

Therefore, if possible, I would simply use System.IO.DriveInfo to get the drive list. If testability is what you need, then I'd wrap it inside a custom class and define an interface for it, something in the sense of:

interface IDriveInfo
{
    string[] GetDrives();
}

But if, due to existing abstractions or so on, you really need to use IFileProvider, you can use CompositeFileProvider in combination with System.IO.DriveInfo to achieve what you want as follows:

public IFileProvider GetFileProvider()
{
    var drives = DriveInfo.GetDrives();
    List<IFileProvider> fileProviders = new List<IFileProvider>();
    foreach(var drive in drives)
    {
        if (drive.IsReady)
        {
            fileProviders.Add(new PhysicalFileProvider(drive.RootDirectory.ToString()));
        }
    }
    return new CompositeFileProvider(fileProviders.ToArray());
}

This still will not give you a list of drives, but you could iterate over the result of GetDirectoryContents to create a list of drives manually.

HashSet<string> drives = new HashSet<string>();
var fp = GetFileProvider();
foreach (var fileInfo in fp.GetDirectoryContents(""))
{
    var pos = fileInfo.PhysicalPath.IndexOf(':');
    var driveLetter =  fileInfo.PhysicalPath.Substring(0, pos+1);
    drives.Add(driveLetter);
}

I tested this on .Net CORE 3.0, but according to the documentation it should work the same for version 2.0: https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.fileproviders.compositefileprovider?view=dotnet-plat-ext-2.0

Related