S h o r t S t o r i e s

// Tales from software development

A Windows Service has a current working directory of C:\Windows\System32

leave a comment »

A warning for the unwary – you might expect that your Windows service is started with its current working directory set to the location of the service executable but it isn’t – it’s set to the Windows System32 directory.

There’s no reason why you shouldn’t change the working directory if it makes sense to do so. As an example of why you might want to, this is how I stumbled across this issue:

The project I’m currently working on uses a Windows service written in C# that communicates with a proprietary medical data store via a Win32 DLL. The .NET Framework successfully locates the DLL when my code calls the functions in the DLL via P/Invoke. I’m guessing that the framework is locating the DLL using a technique similar to the one it uses when probing for referenced assemblies, i.e. it looks in the directory where the entry assembly was loaded from.

The problem I encountered is that the code in the DLL (PASData.dll) looks for its configuration file (PASData.inf) in the current working directory, i.e. C:\Windows\System32 and fails to find it there.

I added the following code to the OnStart() method of the service to set the current working directory:

string assemblyLocationFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (string.Compare(Environment.CurrentDirectory, assemblyLocationFolder, StringComparison.OrdinalIgnoreCase) != 0)
{
    Environment.CurrentDirectory = assemblyLocationFolder;
}
Advertisements

Written by Sea Monkey

January 18, 2010 at 8:00 pm

Posted in Development

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: