Skip to main content
 首页 » 编程设计

c#之如何从我的 C# 程序中获取系统中安装的防病毒软件的路径

2024年08月12日35zlslch

我的 C# 程序需要打开我机器上安装的杀毒软件。

截至目前,我已将路径硬编码如下:

System.Diagnostics.Process.Start("C:/Program Files (x86)/MyAntivirus/myAntivirus.exe"); 

但是路径对于 32 位和 64 位机器是不同的。我无法在我的 64 位 Windows 8.1 机器上运行相同的代码。

有什么方法可以获取安装在我机器上的杀毒软件的路径,以便我的程序独立于机器?

请您参考如下方法:

您可以询问 Windows 路径在哪里,而不是硬编码杀毒软件的路径。大多数防病毒程序都会向 Windows 报告自己。这样 windows 就不会向用户报告没有安装防病毒软件。

使用 WMI,您可以查询该路径的窗口。

var searcherPreVista = new ManagementObjectSearcher(string.Format(@"\\{0}\root\SecurityCenter", Environment.MachineName), "SELECT * FROM AntivirusProduct"); 
var searcherPostVista = new ManagementObjectSearcher(string.Format(@"\\{0}\root\SecurityCenter2", Environment.MachineName), "SELECT * FROM AntivirusProduct"); 
var preVistaResult = searcherPreVista.Get().OfType<ManagementObject>(); 
var postVistaResult = searcherPostVista.Get().OfType<ManagementObject>(); 
 
var instances = preVistaResult.Concat(postVistaResult); 
 
var installedAntivirusses = instances 
    .Select(i => i.Properties.OfType<PropertyData>()) 
    .Where(pd => pd.Any(p => p.Name == "displayName") && pd.Any(p => p.Name == "pathToSignedProductExe")) 
    .Select(pd => new 
    { 
        Name = pd.Single(p => p.Name == "displayName").Value, 
        Path = pd.Single(p => p.Name == "pathToSignedProductExe").Value 
    }) 
    .ToArray(); 
 
foreach (var antiVirus in installedAntivirusses) 
{ 
    Console.WriteLine("{0}: {1}", antiVirus.Name, antiVirus.Path); 
} 

要使用此代码,您需要添加以下 using 语句:

using System; 
using System.Linq; 
using System.Management; 

更进一步。添加对 System.Management 的引用。

此代码将生成所有已安装防病毒软件的列表。列表中的对象将具有名称和路径。如果我运行代码,它会显示以下内容:

Microsoft Security Essentials: C:\Program Files\Microsoft Security Client\msseces.exe