C# – How to C# Library Code know it’s hosting application type without System.Web.dll

ciisnet

We are developing several applications in Visual Studio 2010 using C# and .NET 4.0 on Windows. Two SilverLight applications using services from several WCF projects. Another is a console application.

We want to put some "common" functionality in a separated Library project in order to factorize and reuse code. This library needs to know if the application is hosted (IIS, ASP.NET…) like the WCF services or is running as a console application, due to different file path handling.

Googling this question, people indicates the use of System.Web.dll in order to know if the code is hosted, using HttpContext, HostingEnvironment.IsHosted… The problem is that such approach requires to include a reference to System.Web int he Library project, being not acceptable if this Library will be referenced by a Console project with Client Profile.

The idea is to use another technique that do not involve the use of System.Web assembly.

Best Answer

If you only need to get the path to a file in the folder containing the application (as in the comment on question), you can use:

Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "filename")

For an ASP.NET application, this will be the root folder (same as MapPath("~/" + filename)), for a console application it will be the folder containing the executable.

From the comment to the original question:

when running a as console application, just use the filename as a relative path

I wouldn't recommend using a relative path. This will be relative to the current working directory, which may not be the same as the application directory.