Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a file path to a URL in asp.net core

What the simplest way to convert a file path to a absolute url. Example:

file:

C:\myapp\src\SqlExpress\wwwroot\data\images\test.jpg

url:

http://localhost/data/images/test.jpg
like image 506
Beetlejuice Avatar asked Jun 04 '16 14:06

Beetlejuice


1 Answers

This is what I did. I never could find a way to easily find the wwwroot path outside a controller. So I used a static variable in Startup class, which is accessible throughout the application.

public class Startup
{
    public static string wwwRootFolder = string.Empty;

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        Startup.wwwRootFolder = env.WebRootPath;
        // ...
    }
}

Then in wherever I want..

public static string GetUrlFromAbsolutePath(string absolutePath)
{
    return absolutePath.Replace(Startup.wwwRootFolder, "").Replace(@"\", "/");
}
like image 174
Soundar Rajan Avatar answered Sep 30 '22 09:09

Soundar Rajan