Home > Mobile >  How to get the directory path in a string variable having the given directory name in Asp.Net core A
How to get the directory path in a string variable having the given directory name in Asp.Net core A

Time:09-30

I am trying to get the full path name of the folder 'Images' in API controller. But the following syntax is not working. If Someone can help, it would be very appreciated

string path = HttpContext.Current.Server.MapPath("~/Images/");

CodePudding user response:

You don't need System.Web or HttpContext. You can read the web app's root path from IHostingEnvironment.WebRootPath in ASP.NET Core 2.x, or IWebHostEnvironment.WebPath in ASP.NET Core 3.x.

The dependency injection mechanism knows about that interface which means you can add it as a dependency to your controllers or services, eg :

public class MyController : Controller 
{
    private IWebHostEnvironment _hostingEnvironment;

    public MyController(IWebHostEnvironment environment) {
        _hostingEnvironment = environment;
    }

    [HttpGet]
    public IActionResult Get() {

        var path = Path.Combine(_hostingEnvironment.WebRootPath, "Images");
        ...
    }

You can pass the root path to your class's constructor. After all, a class named ImagesFilesRepository only cares about its local folder, not whether it's hosted on a web or console application. For that to work, the methods should not be static:

public class ImagesFilesRepository 
{

    public ImagesFilesRepository (string rootPath)
    {
        _rootPath=rootPath;
    }

    public DriveService GetService()
    {
         //Operations.... 

    public List<GoogleDriveFiles> GetDriveFiles()
    {
        // Other operations....
    }

}

You can register that class as a service in Startup.cs :

public class Startup
{
    private readonly IWebHostEnvironment _env;

    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
        Configuration = configuration;
        _env = env;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSignleton<GoogleDriveFilesRepository>(_ =>{
            var gdriveRoot=Path.Combine(_env.WebRootPath,"GoogleDriveFiles");
            return new GoogleDriveFilesRepository(gdrivePath);
        });
        ...
    }
}

This class can now be used as a dependency on a controller. It's no longer necessary to use IWebHostEnvironment in the controller :

public class MyController : Controller 

{
    private ImagesFilesRepository _gdrive;

    public MyController(ImagesFilesRepository gdrive) {
        _gdrive=gdrive;
    }
}
  • Related