2013-04-18 39 views
1

我試圖從SERVICES.MSC獲取服務的可執行文件路徑獲得來自SERVICES.MSC C#的服務路徑

我寫了下面的代碼:

var service = ServiceController.GetServices().Where(p => p.ServiceName.Equals("Service name", StringComparison.InvariantCultureIgnoreCase)); 
if (service.Any()) 
//get service data 

我couldn`t找到在哪裏(如果所有)服務可執行文件路徑位於何處?

在services.msc中我可以看到路徑,所以我假設它也可以通過代碼來獲取它。 Example of service info in services.msc (see that executable path exists there)

任何想法?

+0

不知道這將有助於這種情況下,但它可能有助於看看WindowsAPICodePack ShellFile類,看看它是否能幫助訪問這些信息 – Thewads

+1

[**如何使用.net?**]獲得windows服務的phyiscal路徑(http://stackoverflow.com/questions/2728578/how-to-get-phy- tion-path-of-windows-service-using-net)和[ **包含可執行文件路徑的ServiceController類**](http://www.codeproject.com/Articles/26533/A-ServiceController-Class-that-Contains-the-Path-t) – Damith

回答

5

您可以從註冊表中獲得它像這樣:

private static string GetServiceInstallPath(string serviceName) 
{ 
    RegistryKey regkey; 
    regkey = Registry.LocalMachine.OpenSubKey(string.Format(@"SYSTEM\CurrentControlSet\services\{0}", serviceName)); 

    if (regkey.GetValue("ImagePath") == null) 
     return "Not Found"; 
    else 
     return regkey.GetValue("ImagePath").ToString(); 
} 
0

您可以使用WMI來獲得有關服務有關的全部信息(本地或遠程服務)

檢查的(Services+ on CodePlex)代碼如何使用WMI

0

只是有點簡化版本@ ChirClayton代碼:

public string GetServiceInstallPath(string serviceName) => (string) Registry.LocalMachine.OpenSubKey([email protected]"SYSTEM\CurrentControlSet\services\{serviceName}").GetValue("ImagePath"); 

它不會減少可能的服務參數。如果不需要它們,可以使用下列內容:

如果
public string GetServiceInstallPath(string serviceName) 
{ 
    var imagePath = (string) Registry.LocalMachine.OpenSubKey([email protected]"SYSTEM\CurrentControlSet\services\{serviceName}").GetValue("ImagePath"); 
    if (string.IsNullOrEmpty(imagePath)) 
     return imagePath; 
    if (imagePath[0] == '"') 
     return imagePath.Substring(1, imagePath.IndexOf('"', 1) - 1); 
    var indexOfParameters = imagePath.IndexOf(' '); 
    if (indexOfParameters >= 0) 
     return imagePath.Remove(indexOfParameters); 
    return imagePath; 
}