How to call MapPath in WCF services

While working with WCF services hosted in IIS7 with non-HTTP endpoints (such as TCP or NamedPipes), we realized that our usual way to resolve a phisycal file path corresponding to a virtual path on the web server is not supported.

In ASP.NET, we use HttpContext.Current.Server.MapPath method, but HttpContext.Current is null in WCF services with non-HTTP endpoints. What shall we do? It turns out that there is another way to map a virtual path: using the HostingEnvironment class. See the example below.

public static string MapPath(string path)

    if (HttpContext.Current != null)

        return HttpContext.Current.Server.MapPath(path);

    return HostingEnvironment.MapPath(path);


Happy coding!

Welcome to ModelBlog

Thank you for visiting ModelBlog. We hope the time you spend with us will be both entertaining and worth your while. Have fun!