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

China☆狼群 提交于 2019-12-08 14:37:58

问题


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?


回答1:


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



回答2:


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.




回答3:


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

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



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/491735/how-do-i-find-the-install-directory-of-a-windows-service-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!