Asp.Net Core 2.0 - Retrieve Image Url

// Enable directory browsing
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
           Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
                RequestPath = new PathString("/images")
            });
         
            app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
                RequestPath = new PathString("/images")
            });

The above answer is correct, but still could not load the image url, so couple of lines need to add in startup.cs file, i am posting that here


Basically, you need to use IHostingEnvironment and inject it in your service constructor. Then create a string variable with the name of your folder inside the wwwroot let's say "Champions"

Here's the example code:

private readonly IHostingEnvironment hostingEnv;

private const string ChampionsImageFolder = "Champions";

public ChampionsService(IHostingEnvironment hostingEnv){
    this.hostingEnv = hostingEnv;
}

// Suppose this method is responsible for fetching image path
public string GetImage(){
    var path = Path.Combine(hostingEnv.WebRootPath, ChampionsImageFolder);

    return path;
}

What IHostingEnvironment interface does is "Provides information about the hosting environment an application is running in."

If you want to get files inside a given path, this will give you a hint.

var directoryFiles = Directory.GetFiles("wwwroot/Champions");

foreach (var item in directoryFiles)
{
    // do something here
}

If you want to create path link from those wwwroot folder, you need register in your startup the UseDirectoryBrowser

Inside your Startup.cs file, Find the Configure method insert this code snippet

These code snippets will expose files inside the Champions directory and create a new route on your website which is ChampionImages derived from folder Champions in your wwwroot

app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "Champions")),
    RequestPath = new PathString("/ChampionImages")
});

Then you can now use something like this localhost:8080/ChampionImages where you can see each file stored inside the Champions folder of your wwwroot. What you can do to create a URL of that image is something like this.

var imageUrl = $"/ChampionImages/{exactFileName}"; // this will create a string link.

I hope this simple code snippets give you help or idea :)