views:

526

answers:

3

I've created a very simple .NET Windows Service and installed it using InstallUtil.exe utility.

In the service I have a piece of code as such:

if (File.Exists("test_file.txt"))
{
   // Do something clever
}

I've created a file called test_file.txt in the same directory as the service but the commented part of the code is never being executed...?

A: 

It normally starts in the windows directory

1800 INFORMATION
That was my thought as well..
CSharpAtl
Actually, the default location is in %windir%\system32 .
Harper Shelby
+1  A: 

Services are started from an application called Service Control Manager. This application lives in the system directory %WinDir%\System32

For more information about Service Control Manager see http://msdn.microsoft.com/en-us/library/ms685150(VS.85).aspx

Thanks Harper Shelby for pointing out problem with orginal post.

JD
svchost.exe is a service host for most internal windows services. Services can, and in the case of non-Windows services most likely do, run in a different exe host.
Michael
Right directory, wrong reason.
Harper Shelby
Thanks - dropping the file in there makes it work so I can confirm that location: c:\windows\system32
Guy
What's the right reason Harper?
Guy
@Guy - I was trying to research that. I can't find a 'good' reason, though I suspect it's because that's the directory that the SCM (Service Control Manager) runs from, and so it gets passed to the child process (the service) from the parent process's environment.
Harper Shelby
Services are started by the Service Control Manager (services.exe) which also resides in %WINDIR%\system32. See http://en.wikipedia.org/wiki/Service_Control_Manager
0xA3
+6  A: 
System.Diagnostics.Trace.WriteLine(Directory.GetCurrentDirectory());

will output the current directory. Put that code in the startup method of your service and use a tool like DebugView to check the output. Then you will know the startup folder of your service.

This simple technique will be useful with many problems in service development, especially to debug service startup.

You probably expected the working folder of your service to be the folder where the service executable is in (so did I). You can change to that folder using the following lines of code:

System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
0xA3
That's a very cool tip - thanks!
Guy