views:

2293

answers:

4

I'm pretty sure that a Windows service gets C:\winnt (or similar) as its working directory when installed using InstallUtil.exe. Is there any way I can access, or otherwise capture (at install time), the directory from which the service was originally installed? At the moment I'm manually entering that into the app.exe.config file, but that's horribly manual and feels like a hack.

Is there a programmatic way, either at run time or install time, to determine where the service was installed from?

+3  A: 

Do you mean you want the directory containing the assembly? If so, that's easy: use Assembly.Location.

I wouldn't try to change the working directory of the process though - I wouldn't be surprised if that had nasty side effects, if indeed you're allowed to do it.

Jon Skeet
Thanks, Jon. You were right, the question was not worded quite correctly, so I've changed it.
endian
+2  A: 

InstallUtil.exe calls ServiceInstaller.Install() of your application at install time.

Override it, add it to the list of your project's Installers and get any information you need.

Quassnoi
Thanks. The runtime approaches of Jon and Steve are actually a better fit for what I need to do.
endian
+10  A: 

You can use reflection to get the location of the executing assembly. Here's a simple routine that sets the working directory to the location of the executing assembly using reflection:


String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
path = System.IO.Path.GetDirectoryName(path);
Directory.SetCurrentDirectory(path);

Steve Wranovsky
Thanks! May I suggest the System.IO.Path class rather than doing string.SubString() ?
endian
Thanks for the feedback, that's a better way to get the root of a directory.
Steve Wranovsky
+1  A: 

I did not know the Directory.SetCurrentDirectory method. Usually I do:

Environment.CurrentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;

Ramon