0

I have some JSON data-configuration files that I wish to have them online as static files and read them upon my web-service initialization. So, I wish to access them internally from my code, not to make them public to external access.

Following the instructions (below) I placed them inside a /wwwroot/Static folder and used app.UseStaticFiles(); in Startup.Configure(), then I try to read them via both HTML and C# code using the "~/Static/*.json" notation but it does not work from C# code.

When locally, I am getting error: DirectoryNotFoundException: Could not find a part of the path '...\Repos\VS2019\my-project-folder\~\Static\filename.json'.

So, the ~ symbol is not translated to wwwroot folder name.

When online (as Azure App Service) I am getting: HTTP ERROR 500

What I have done wrong?

jps
  • 20,041
  • 15
  • 75
  • 79

1 Answers1

0

Use HostingEnvironment to get physical location:

public HomeController(IHostingEnvironment hostingEnvironment)
    {
        string data= System.IO.File.ReadAllText(hostingEnvironment.WebRootPath.ToString()+ @"\Static\test.json");
    }

if Application is web Api then use ContentRoot instead of WebRootPath.

Always_a_learner
  • 1,254
  • 1
  • 8
  • 16
  • Thank you learner! I also found a more verbally detailed solution at https://stackoverflow.com/questions/60455519/how-do-i-resolve-a-local-file-path-in-asp-net-core-3 – Yiannis Manatos Jun 25 '20 at 12:02