Syncfusion AI Assistant

How can I help you?

Getting started with ASP.NET Core File Manager Control

27 May 202622 minutes to read

This section briefly explains about how to include ASP.NET Core FileManager control in your ASP.NET Core application using Visual Studio.

Prerequisites

System requirements for ASP.NET Core controls

Create ASP.NET Core web application with Razor pages

Create an ASP.NET Core Razor Pages project using Visual Studio:

  1. Start Visual Studio and select Create a new project.

  2. In the Create a new project window, choose ASP.NET Core Web App (Razor Pages)Next.

  3. In the Configure your new project dialog, specify the project name (and optionally change location/folder).

  4. Click Next.

  5. In the Additional information dialog:
    • Select .NET 10.0.
    • Verify: Do not use top-level statements is unchecked.
  6. Click Create.

For alternative approaches to create the project, see Create a new project in Visual Studio.

Install ASP.NET Core package in the application

To add ASP.NET Core controls in the application, open the NuGet package manager in Visual Studio (Tools → NuGet Package Manager → Manage NuGet Packages for Solution), search for Syncfusion.EJ2.AspNet.Core and then install it. Alternatively, you can utilize the following package manager command to achieve the same.

Install-Package Syncfusion.EJ2.AspNet.Core -Version 33.2.3

Create an ASP.NET Core Razor Pages project using Visual Studio Code:

  • Install the latest .NET SDK that supports .NET 10.0 or later.
  • Open Visual Studio Code.
  • Press Ctrl + ` to open the integrated terminal.
  • Run the following commands:
dotnet new webapp -o RazorPagesMovie

code -r RazorPagesMovie

Install ASP.NET Core package in the application

To integrate the Syncfusion® ASP.NET Core DataGrid component, install the required Syncfusion.EJ2.AspNet.Core NuGet packages using the integrated terminal:

  1. Press Ctrl + ` to open the integrated terminal in Visual Studio Code.
  2. Navigate to the directory containing the .csproj file.
  3. Run the following commands to install the packages:
dotnet add package Syncfusion.EJ2.AspNet.Core --version 33.2.3

NOTE

Syncfusion® ASP.NET Core controls are available in nuget.org. Refer to NuGet packages topic to learn more about installing NuGet packages in various OS environments. The Syncfusion.EJ2.AspNet.Core NuGet package has dependencies, Newtonsoft.Json for JSON serialization and Syncfusion.Licensing for validating Syncfusion® license key.

Add Syncfusion® ASP.NET Core Tag Helper

Open ~/Pages/_ViewImports.cshtml file and import the Syncfusion.EJ2 TagHelper.

@addTagHelper *, Syncfusion.EJ2

Add stylesheet and script resources

Here, the theme and script is referred using CDN inside the <head> of ~/Pages/Shared/_Layout.cshtml file as follows,

<head>
    ...
    <!-- Syncfusion ASP.NET Core controls styles -->
    <link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/33.2.3/fluent.css" />
    <!-- Syncfusion ASP.NET Core controls scripts -->
    <script src="https://cdn.syncfusion.com/ej2/33.2.3/dist/ej2.min.js"></script>
</head>

NOTE

Checkout the Themes topic to learn different ways (CDN, NPM package, and CRG) to refer styles in ASP.NET Core application, and to have the expected appearance for Syncfusion® ASP.NET Core controls.

NOTE

Checkout the Adding Script Reference topic to learn different approaches for adding script references in your ASP.NET Core application.

Register Syncfusion® Script Manager

Also, register the script manager <ejs-scripts> at the end of <body> in the ASP.NET Core application as follows.

<body>
    ...
    <!-- Syncfusion ASP.NET Core Script Manager -->
    <ejs-scripts></ejs-scripts>
</body>

Add ASP.NET Core File Manager control

Now, add the Syncfusion® ASP.NET Core File Manager tag helper in ~/Pages/Index.cshtml page.

Create a Controllers folder in the project and add a HomeController.cs file with the following code. Also, create a wwwroot/Files folder to store the files for the File Manager access.

<div class="control-section">
    <div class="sample-container" style="padding:10px">        
        <!--  Filemanager control declaration -->
        <ejs-filemanager id="file">
            <e-filemanager-ajaxsettings url="/Home/FileOperations">
            </e-filemanager-ajaxsettings>
            <e-filemanager-contextmenusettings visible="false"></e-filemanager-contextmenusettings>
            <e-filemanager-navigationpanesettings visible="false"></e-filemanager-navigationpanesettings>
            <e-filemanager-toolbarsettings visible="false"></e-filemanager-toolbarsettings>
        </ejs-filemanager>
    </div>
</div>
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Cors;
using Syncfusion.EJ2.FileManager.Base;
using Syncfusion.EJ2.FileManager.PhysicalFileProvider;

// Replace `FileManagerProject` with your project name.
namespace FileManagerProject.Controllers
{
    [Route("[controller]")]
    public class HomeController : Controller
    {
        public PhysicalFileProvider operation;
        public string basePath;
        string root = "wwwroot\\Files";

        public HomeController(IWebHostEnvironment hostingEnvironment)
        {
            this.basePath = hostingEnvironment.ContentRootPath;
            this.operation = new PhysicalFileProvider();
            this.operation.RootFolder(this.basePath + "\\" + this.root);
        }
        [Route("FileOperations")]
        public object FileOperations([FromBody] FileManagerDirectoryContent args)
        {
            var fullPath = (this.basePath + "\\" + this.root + args.Path).Replace("/", "\\");
            if (args.Action == "delete" || args.Action == "rename")
            {
                if ((args.TargetPath == null) && (args.Path == ""))
                {
                    FileManagerResponse response = new FileManagerResponse();
                    response.Error = new ErrorDetails { Code = "401", Message = "Restricted to modify the root folder." };
                    return this.operation.ToCamelCase(response);
                }
            }
            switch (args.Action)
            {
                case "read":
                    // reads the file(s) or folder(s) from the given path.
                    return this.operation.ToCamelCase(this.operation.GetFiles(args.Path, args.ShowHiddenItems));
                case "delete":
                    // deletes the selected file(s) or folder(s) from the given path.
                    return this.operation.ToCamelCase(this.operation.Delete(args.Path, args.Names));
                case "copy":
                    // copies the selected file(s) or folder(s) from a path and then pastes them into a given target path.
                    return this.operation.ToCamelCase(this.operation.Copy(args.Path, args.TargetPath, args.Names, args.RenameFiles, args.TargetData));
                case "move":
                    // cuts the selected file(s) or folder(s) from a path and then pastes them into a given target path.
                    return this.operation.ToCamelCase(this.operation.Move(args.Path, args.TargetPath, args.Names, args.RenameFiles, args.TargetData));
                case "details":
                    // gets the details of the selected file(s) or folder(s).
                    return this.operation.ToCamelCase(this.operation.Details(args.Path, args.Names, args.Data));
                case "create":
                    // creates a new folder in a given path.
                    return this.operation.ToCamelCase(this.operation.Create(args.Path, args.Name));
                case "search":
                    // gets the list of file(s) or folder(s) from a given path based on the searched key string.
                    return this.operation.ToCamelCase(this.operation.Search(args.Path, args.SearchString, args.ShowHiddenItems, args.CaseSensitive));
                case "rename":
                    // renames a file or folder.
                    return this.operation.ToCamelCase(this.operation.Rename(args.Path, args.Name, args.NewName, false, args.ShowFileExtension, args.Data));
            }
            return null;
        }

        // uploads the file(s) into a specified path
        [Route("Upload")]
        [DisableRequestSizeLimit]
        public IActionResult Upload(string path, long size, IList<IFormFile> uploadFiles, string action)
        {
            try
            {
                FileManagerResponse uploadResponse;
                foreach (var file in uploadFiles)
                {
                    var folders = (file.FileName).Split('/');
                    // checking the folder upload
                    if (folders.Length > 1)
                    {
                        for (var i = 0; i < folders.Length - 1; i++)
                        {
                            string newDirectoryPath = Path.Combine(this.basePath + path, folders[i]);
                            if (Path.GetFullPath(newDirectoryPath) != (Path.GetDirectoryName(newDirectoryPath) + Path.DirectorySeparatorChar + folders[i]))
                            {
                                throw new UnauthorizedAccessException("Access denied for Directory-traversal");
                            }
                            if (!Directory.Exists(newDirectoryPath))
                            {
                                this.operation.ToCamelCase(this.operation.Create(path, folders[i]));
                            }
                            path += folders[i] + "/";
                        }
                    }
                }
                uploadResponse = operation.Upload(path, uploadFiles, action, size, null);
                if (uploadResponse.Error != null)
                {
                    Response.Clear();
                    Response.ContentType = "application/json; charset=utf-8";
                    Response.StatusCode = Convert.ToInt32(uploadResponse.Error.Code);
                    Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = uploadResponse.Error.Message;
                }
            }
            catch (Exception e)
            {
                ErrorDetails er = new ErrorDetails();
                er.Message = e.Message.ToString();
                er.Code = "417";
                er.Message = "Access denied for Directory-traversal";
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.StatusCode = Convert.ToInt32(er.Code);
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = er.Message;
                return Content("");
            }
            return Content("");
        }

        // downloads the selected file(s) and folder(s)
        [Route("Download")]
        public IActionResult Download(string downloadInput)
        {
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            };
            FileManagerDirectoryContent args = JsonSerializer.Deserialize<FileManagerDirectoryContent>(downloadInput, options);
            return operation.Download(args.Path, args.Names, args.Data);
        }

        // gets the image(s) from the given path
        [Route("GetImage")]
        public IActionResult GetImage(FileManagerDirectoryContent args)
        {
            return this.operation.GetImage(args.Path, args.Id, false, null, null);
        }
    }
}

After creating a controller for the File Manager service, register it in the Program.cs file using:

   app.MapControllers();

Press Ctrl+F5 (Windows) or +F5 (macOS) to run the app. Then, the Syncfusion® ASP.NET Core File Manager control will be rendered in the default web browser.

File Manager getting started

NOTE

The File Manager can be rendered with local service for sending ajax request. Ajax request will be sent to the server which then processes the request and sends back the response. Refer Controller file for File Manager service.

See also