Christian
Christian

Reputation: 1194

asp.net core fileprovider get all drives

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

Upvotes: 3

Views: 2641

Answers (2)

devb
devb

Reputation: 279

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://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.fileproviders.compositefileprovider?view=dotnet-plat-ext-2.0

Upvotes: 1

Niladri
Niladri

Reputation: 5962

you have to use the namespace Microsoft.Extensions.FileProviders; in your REST API controller and startup file to use the PhysicalFileProvider class that implements the IFileProvider interface. You can use GetDirectoryContents() method to iterate the files.

Check the below links for a detail example to get files from a root directory

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/file-providers

http://www.c-sharpcorner.com/article/file-providers-in-asp-net-core/

https://www.codeproject.com/Articles/1204104/ASP-NET-Core-File-Providers

Upvotes: 1

Related Questions