[英]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. 我很确定使用InstallUtil.exe安装时,Windows服务会将C:\\ winnt(或类似)作为其工作目录。 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. 目前我手动将其输入到app.exe.config文件中,但这是可怕的手动,感觉就像一个黑客。
Is there a programmatic way, either at run time or install time, to determine where the service was installed from? 是否在运行时或安装时有一种编程方式来确定服务的安装位置?
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);
Do you mean you want the directory containing the assembly? 你的意思是你想要包含程序集的目录吗? If so, that's easy: use Assembly.Location
. 如果是这样,那很简单:使用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. 我不会尝试改变过程的工作目录 - 如果它有令人讨厌的副作用我不会感到惊讶,如果确实你被允许这样做的话。
I did not know the Directory.SetCurrentDirectory
method. 我不知道Directory.SetCurrentDirectory
方法。 Usually I do: 通常我这样做:
Environment.CurrentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
Though very late, but it may help somebody. 虽然很晚,但它可能对某人有所帮助。 I solved this issue by using AppDomain.CurrentDomain.BaseDirectory 我通过使用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. AppDomain.CurrentDomain.BaseDirectory给出了实际安装Windows服务的目录,而不是C:\\ Windows \\ system32 \\ path。
I saw it later that @Ramon has already posted the same solution. 我后来看到@Ramon已经发布了相同的解决方案。
InstallUtil.exe
calls ServiceInstaller.Install()
of your application at install time. InstallUtil.exe
在安装时调用应用程序的ServiceInstaller.Install()
。
Override it, add it to the list of your project's Installers
and get any information you need. 覆盖它,将其添加到项目的Installers
列表中,并获取所需的任何信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.