我有一个windows服务,它可以获取工作站上所有已安装的服务。现在,我想要获取特定服务的可执行文件的位置。路径必须是绝对路径。我怎样才能通过编程实现这一点呢?
发布于 2012-06-06 18:25:40
我不太了解.net接口,但是如果你不能找到一种方法来读取每个服务的注册表值: LocalMachine/System/CurrentControlSet/Services/SERVICENAME,然后你需要访问显示完整路径的ImagePath键(如果不是绝对路径,那么基本路径就是windows主文件夹)
我也找到了一个例子:http://bytes.com/topic/c-sharp/answers/268807-get-path-install-service
发布于 2016-11-02 22:56:01
我最近需要这个,这就是我创建的。在给定的代码中,我检查匹配的imagePath
,但是可以很容易地修改它以返回imagePath
,并且它已经返回了匹配的服务名称。您可以在此循环中{foreach (string keyName...}
检查keyName
并返回imagePath
。工作起来很有魅力,但请记住,会有安全性和用户访问方面的考虑。如果用户没有访问权限,它可能会失败。我的用户“以管理员身份”运行它,从这个意义上说,我没有问题
// currPath - full file name/path of the exe that you trying to find if it is registered as service
// displayName - service name that you return if you find it
private bool TryWinRegistry(string currPath, out string displayName)
{
displayName = string.Empty;
try
{
using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\services", false))
{
if (regKey == null)
return false;
// we don't know which key because key name is configured by config file and equals to service name
foreach (string keyName in regKey.GetSubKeyNames())
{
try
{
using (RegistryKey serviceRegKey = regKey.OpenSubKey(keyName))
{
if (serviceRegKey == null)
continue;
string val = serviceRegKey.GetValue("imagePath") as string;
if (val != null && String.Equals(val, currPath, StringComparison.OrdinalIgnoreCase))
{
displayName = serviceRegKey.GetValue("displayName") as string;
return true;
}
}
}
catch
{
}
}
}
}
catch
{
return false;
}
return false;
}
https://stackoverflow.com/questions/10912137
复制相似问题