您好,這是我在Stackoverflow上的第一篇文章。C#WMI ManagementException拋出search.Get()。計數
背景: 我正在構建一個類,使用WindowsManagementInstrumentation庫來查詢DNS服務器。
問題: 當我搜索一個DNS記錄不DNS服務器出現以下錯誤上存在: 型「System.Management.ManagementException」的異常出現在System.Management.dll但沒有在用戶代碼
正是從這一行造成的處理:
if (search.Get().Count > 0)
在看這條線,我發現該異常被計數。
我不知道爲什麼會發生這種情況。如果我搜索我知道的DNS服務器上的DNS記錄,那麼Count會返回正確的數字並且不會引發錯誤。如果Count在服務器上找不到DNS記錄,我希望Count返回0。我可以做一個嘗試捕捉,當它拋出異常處理它在我的最後,所以它但我覺得這是不正確的做法。有任何想法嗎?
我調試時出現以下錯誤信息。
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
完整的方法:
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;
}
很抱歉,如果我錯過了什麼,並感謝您的幫助。
不知道這是否有幫助,但我經常在Powershell中使用WMI調用,而且我發現即使返回了一個對象,.Count屬性有時也可能爲null。我認爲這會拋出一個更明確的例外,但我會首先檢查Count屬性是否爲空。作爲一個方面說明,我認爲圍繞search.Get()包裝try catch不會有問題。 –