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");


Edit this Article
asp.net Core 3.1 asp.net mvc asp.net core errors asp.net web forms asp.net core tutorial Technology published
Was this page helpful?
Yes Yes! this solution to the problem was helpful. No No! this solution to the problem was not helpful.. Leave ErnesTech Feedback.Feedback
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.

Your Session is Ending
Login to Continue

© 2021 - ErnesTech - Privacy