Just so anyone else who runs across this knows what I ended up doing. I ended up wrapping the count check in a try catch and if it throws an exception I ignore it and just return an empty rrecords object since the search didn't find anything.
C# WMI ManagementException thrown on search.Get().Count
Question
Hello this is my first post on Stackoverflow.
Background: I am building a Class to use the WindowsManagementInstrumentation library to query DNS Servers.
Problem: When I search for a dns record that does not exist on the DNS Server I get the following error: An exception of type 'System.Management.ManagementException' occurred in System.Management.dll but was not handled in user code
It is caused from this line:
if (search.Get().Count > 0)
In looking at this line I found the exception is on the Count.
I am not sure why this happens. If I search for a DNS Record that I know is on the DNS Server then Count returns the correct number and doesn't throw an error. I expect Count to return 0 if it can't find a DNS Record on the server. I could do a try catch and when it throws the exception handle it on my end so it but I feel this is not the right way to do it. Any ideas?
I get the following error info when I debug.
Count 'Count' threw an exception of type 'System.Management.ManagementException' int {System.Management.ManagementException}
base {"Generic failure "} System.SystemException {System.Management.ManagementException}
base {"Generic failure "} System.Exception {System.Management.ManagementException}
Data {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
HelpLink null string
HResult -2146233087 int
InnerException null System.Exception
Message "Generic failure " string
Source "System.Management" string
StackTrace " at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)\r\n at System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()\r\n at System.Management.ManagementObjectCollection.get_Count()" string
ErrorCode Failed System.Management.ManagementStatus
Full Method:
public List<ManagementObject> GetRecords(string domain, string name, string type)
{
//Object to hold list of RRecords/DNS Records
List<ManagementObject> rrecords = new List<ManagementObject>();
//Init properites for the given type
Properties propertiesStruct = new Properties(type);
//Query
string query = "SELECT * FROM " + propertiesStruct.Table + " WHERE DomainName = '" + domain.ToLower() + "' AND OwnerName ='" + name.ToLower() + "." + domain.ToLower() + "'";
//Search for results
ManagementObjectSearcher search = new ManagementObjectSearcher(this.scope, new ObjectQuery(query));
//Make sure we have something and if we do loop through them to grab the data
if (search.Get().Count > 0)
{
foreach (ManagementObject results in search.Get())
{
rrecords.Add(results);
}
}
return rrecords;
}
Sorry if I missed anything and thanks for the help.
Solution