Beetlejuice
Beetlejuice

Reputation: 4425

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

Upvotes: 9

Views: 9128

Answers (2)

Soundar Rajan
Soundar Rajan

Reputation: 352

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(@"\", "/");
}

Upvotes: 9

Ian
Ian

Reputation: 624

    static string Convert(string path)
    {
        return path.Replace(@"C:\myapp\src\SqlExpress\wwwroot", @"http://localhost").Replace('\\', '/');
    }

    static void Main(string[] args)
    {
        string url = Convert(@"C:\myapp\src\SqlExpress\wwwroot\data\images\test.jpg");
    }

Upvotes: -2

Related Questions