FIX: nHibernate/log4net in windows service. FileNotFoundException

20 January 2011 Off By David

When using nHibernate in a windows service you may find that you encounter FileNotFoundExceptions when trying to load assemblies or external configuration files. Typically this is in scenarios where you are running your service under a user context such as NetworkService.

If you hunt around long enough you will find that it is trying to locate said files in the %WINDIR%\system32 folder (for example c:\windows\system32), and not from the services own directory.

By default window services set the default directory to the %WINDIR%\system32.

Simply change your service’s default directory to wherever your service is running.

Here’s a sample:

// Set current directory to assembly folder
// Need to to this so can find the configuration file for the logger
// default is %WINDIR%\system32 for window services
static void Main(string[] args) {
	Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location); ///... }