abreneliere abreneliere - 1 month ago 13
ASP.NET (C#) Question

How to access a file from IIS web service hosted by ServiceHost

In my IIS application I open a file located in the wwwroot directory that way:

File.ReadAllText("ConfigFile.json");


IISExpress tries to open the file in
C:\Program Files (x86)\IIS Express\ConfigFile.json


I thought the wwwroot directory was the working directory but apparently it's not the case.

Log4net log files are written relatively to the working directory, and configuration manager files also. So I don't understand why opening a file with System.IO.File I have
C:\Program Files (x86)\IIS Express
as the working directory.

What's the best solution for that problem ? I suppose I don't have to touch the Current defined working directory.

Answer

Ok, the solution that works in a IIS WCF Service, hosted by a ServiceHost class is:

System.Web.Hosting.HostingEnvironment.MapPath("/ConfigFile.json")

It gives the full absolute path that is valid in my IIS Express environment and in the deployed IIS environment.

If I remove the '/' it throws the error:

The relative virtual path 'X' is not allowed here.

The option serviceHostingEnvironment aspNetCompatibilityEnabled="true" does not change anything.

Thanks to VDWWD that helped to find the solution.