Have a look at the following source code
private IEnumerable<string> GetAntivirusSoftwareFromNamespace(string @namespace)
{
try
{
var wmipathstr = string.Format(@"\\{0}{1}", Environment.MachineName, @namespace);
var searcher = new ManagementObjectSearcher(wmipathstr, "SELECT * FROM AntivirusProduct");
return from ManagementObject managementObject in searcher.Get()
select managementObject.Properties["displayName"].Value.ToString();
}
catch
{
// ignored
}
return Enumerable.Empty<string>();
}
And I call it with the following piece of code
antivirusSoftware.AddRange(GetAntivirusSoftwareFromNamespace(@"\root\SecurityCenter"));
antivirusSoftware.AddRange(GetAntivirusSoftwareFromNamespace(@"\root\SecurityCenter2"));
As you can see, the expcetion is ignored - which works fine on my computer. However if I run it on my staging server (which is Windows Server 2016 Standard) the exception is still thrown. Here's the stack trace
Unbehandelte Ausnahme: System.Management.ManagementException: Ungültige Klasse bei System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode) bei System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext() bei System.Linq.Enumerable.d__94`1.MoveNext() bei System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
bei System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) bei protocol.client.Service.Modules.Information.InformationService.GetAntivirusSoftware() in C:\TeamCity\buildAgent\work\a41c7d46cc4907de\src\client\Service\Modules\Information\InformationService.cs:Zeile 70.
Any idea what could be the cause on this or how to fix it? I don't have visual studio or a debugger installed on the staging server.
The exception isn't thrown within the method you've shown - you're basically returning a query to the caller, and that query is then failing.
One option would be to force the query to execute immediately by calling ToList()
. That way, any exceptions would be thrown within the method itself, so you could catch them:
return searcher.Get()
.Select(mo => mo.Properties["displayName"].Value.ToString())
.ToList();
Having said that, I'd strongly advise against having such an empty, blanket catch block - that basically says, "I don't care what's gone wrong, I want my code to keep running regardless, and I don't even want to log what the problem is." If you want to guard against ManagementException
, catch that specific exception instead - and consider logging it so you can try to avoid it in future.
See more on this question at Stackoverflow