ASP.NET Core 3.1 Get the Path to the Images Folder Without Hard Coding Back-Slash or Forward-Slash Cross-Platform Hosting Environment


Problem: How do you get the path to the wwwroot folder to show an image without breaking the code in Cross-Platform hosting (Linux or Windows).

Solution: When developing an Asp.Net Core 3.1 Application, there will be a chance one day you would like to host the application in Linux Hosting Environment. As a developer, you might be wondering how to implement code to retrieve the URL path to the images folder or any web resouces without breaking code when using backlashes or forward slashes as required by Linux or Windows Operation System.

1. Make sure the Action returning the URL Path does not hard code or use any backslashes or forward-slashes instead use:
  var pathToImage = Path.Combine("ImageFolder","AnotherFolder","ImageName.Extenstion");
-When you use Path.Combine, regardless of the Hosting Environment, the Operating System requirement to absolute paths is still respected, this way your application does not break when deployed to either Linux or Windows.

2. In the Razor View, you could then use the variable returned along with the Model Object you are working with. For example, in the HTML Image tag, you could show an image like this;  img [email protected]

3. When you find that the path to the file conent is being appended to the complete domain url and the image display works on the application home page but breaks on any other page, include the "~" in your Path.Combine directive.
       For Example var pathToImage = Path.Combine("~","ImageFolder");





prednisoneM said:

I needs to spend some time learning much more or understanding more.

Posted On: January 10, 2023 21:48:15 PM


For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email Address[email protected]