FoxDeploy
FoxDeploy

Reputation: 13537

Asp.net DirectoryBrowser Feature, how to control sort?

I've got an asp.net core webapp which uses the directory browser feature setup in my Startup.cs like this.

app.UseDirectoryBrowser(new DirectoryBrowserOptions
    {
        FileProvider = new PhysicalFileProvider(
     Path.Combine(Directory.GetCurrentDirectory(), "youtubeDLs")),
        RequestPath = "/Downloads"
    });

I surface this as a partial like this.

<div id="dynamicContentContainer"></div>
<script>
    setTimeout(function () {
        $("#dynamicContentContainer").load("/Downloads")
    }, 2800);

</script>

And this is great, I have my file browser which I want, it's lovely.

enter image description here

BUT, I don't have any control on file sorting, and I'd love to sort the files on DateModified or DateCreated.

I've scoured the API Catalog on MSDN but can't find anything. Is this just something I can't control?

Upvotes: 1

Views: 726

Answers (3)

jan-hybs
jan-hybs

Reputation: 724

You can simply override HtmlDirectoryFormatter

public class SortedHtmlDirectoryFormatter : HtmlDirectoryFormatter
{
    public SortedHtmlDirectoryFormatter(HtmlEncoder encoder) : base(encoder) { }

    public override Task GenerateContentAsync(HttpContext context, IEnumerable<IFileInfo> contents)
    {
        var sorted = contents.OrderBy(f => f.LastModified);
        return base.GenerateContentAsync(context, sorted);
    }
}

and use it in your app:

app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
    FileProvider = staticPathProvider,
    RequestPath = "/Downloads",
    Formatter = new SortedHtmlDirectoryFormatter(HtmlEncoder.Default)
});

Upvotes: 8

lastr2d2
lastr2d2

Reputation: 3968

I made this simple nuget package SortedHtmlDirectoryFormatter according to Elendil's suggestion.

app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
    FileProvider = new PhysicalFileProvider(rootDirectory),
    RequestPath = "/your-request-path",
    Formatter = new SortedHtmlDirectoryFormatter()
});

This will sort the file list by LastModified in descending order.

Upvotes: 2

Elendil Zheng-MSFT
Elendil Zheng-MSFT

Reputation: 541

Actually there is no options to config sort in this middleware, I've raised this issue in github. Asp.net core has no plan to add this feature either. since UseDirectoryBrowser is more like a diagnostic tool. To achieve this you'd better replace DirectoryBrowserOptions.Formatter to customize the view. You can copy HtmlDirectoryFormatter and customize it to your liking.

Upvotes: 2

Related Questions