How to get working path of a wcf application?

I want to get the working folder of a WCF application. How can I get it?

If I try

HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath)

I get a null reference exception (the Http.Current object is null).


What I meant with the working folder was the folder where my WCF service is running. If I set aspNetCompatibilityEnabled="true", I get this error:

The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.


Solution 1:

I needed the same information for my IIS6 hosted WCF application and I found that this worked for me:

string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

As always, YMMV.

Solution 2:

Please see ongle's answer below. It is much better than this one.

Updated after more information

The following worked for me. I tested it with a new WCF Service I hosted on IIS through a Service1.svc.

  1. Add <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> to web config. <system.serviceModel>..</ ..> existed already.
  2. Add AspNetCompatibilityRequirementsAttribute to the service with Mode Allowed.
  3. Use HttpContext.Current.Server.MapPath("."); to get the root directory.

Below is the full code for the service class. I made no changes in the IService1 interface.

[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
    public void DoWork()
    {
        HttpContext.Current.Server.MapPath(".");
    }
}

And below is an excerpt from the web.config.

<system.serviceModel>
    <!-- Added only the one line below -->
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

    <!-- Everything else was left intact -->
    <behaviors>
        <!-- ... -->
    </behaviors>
    <services>
        <!-- ... -->
    </services>
</system.serviceModel>

Old answer

What do you mean by the Working Folder? WCF services can be hosted in several different ways and with different endpoints so working folder is slightly ambiguous.

You can retrieve the normal "Working folder" with a call to Directory.GetCurrentDirectory().

HttpContext is an ASP.Net object. Even if WCF can be hosted on IIS, it's still not ASP.Net and for that reason most of the ASP.Net techniques do not work by default. OperationContext is the WCF's equivalent of HttpContext. The OperationContext contains information on the incoming request, outgoing response among other things.

Though the easiest way might be to run the service in ASP.Net compatibility mode by toggling it in the web.config. This should give you access to the ASP.Net HttpContext. It will limit you to the *HttpBindings and IIS hosting though. To toggle the compatibility mode, add the following to the web.config.

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>