Search code examples
c#asp.netoutput-directory

Output directory path both locally and on remote server for ASP.NET Web Service


I've builded a ASP.NET RESTful service project with C#. I need to add some custom XML files with configuration, which I need to read and process at runtime.

I added the XML files to my project and set the property "Copy to Output Directory" as "Copy Always".

To open the file I used the following snippet:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "configuration.xml");

This works fine when I publish the project to the server but if I run the web services locally the output directory changes and I have to append bin to the beginning of the path like:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin\\configuration.xml");

Is there any way to get the correct output directory for both local and remote server?


Solution

  • What you could do instead of copying your files to the output folder is to keep them in the root project folder (or some sub-folder structure) and use the HttpServerUtility.MapPath() method to resolve the correct physical path to the file on the server (both local and remote).

    So in your scenario, HttpContext.Current.Server.MapPath("configuration.xml") would return a path like C:\MyWebApp\configuration.xml which you can then load as normal.