endian
endian

Reputation: 4294

How do I find the install directory of a Windows Service, using C#?

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?

Upvotes: 19

Views: 32033

Answers (5)

DiligentKarma
DiligentKarma

Reputation: 5328

Though very late, but it may help somebody. I solved this issue by using AppDomain.CurrentDomain.BaseDirectory

string someFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\Resources\SomeResource.xml";

AppDomain.CurrentDomain.BaseDirectory gave the directory where the windows service was actually isntalled, not the C:\Windows\system32\ path.

I saw it later that @Ramon has already posted the same solution.

Upvotes: 4

Ramon Smits
Ramon Smits

Reputation: 2618

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

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

Upvotes: 5

Steve Wranovsky
Steve Wranovsky

Reputation: 5713

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);

Upvotes: 36

Quassnoi
Quassnoi

Reputation: 425341

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.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500275

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.

Upvotes: 7

Related Questions