简体   繁体   中英

ManagementObjectSearcher error

Some of our customers inform us that in some cases following error appears:

System.Management.ManagementException: Błąd dostawcy.
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()

The error is generated while trying to loop through a colection returned by Get() method of the System.Mamangment.ManagementObjectSearcher object.

This is the code of my method:

private bool PrinterExists(string printerName)
{
    bool retVal = false;
    SelectQuery q = new SelectQuery("select caption from win32_printer");
    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(q))
    {
        foreach (ManagementObject printer in searcher.Get())
        {
            if(printer["Caption"].ToString() == printerName)
            {
                retVal = true;
                break;
            }
        }
    }
    return retVal;
}

It seems that the problem appears only on Windows XP. The only workaround I know is reconstruction of WMI database. It sometimes helps, but unfortunatelly not always.

Can anyone tell me what is the reason of this error and how can I fix it?

There a many possible reasons you could get an error while enumerating a WMI collection, including that you don't have permissions to look at some properties of an object. You can check the permissions possibility by running the app as administrator and seeing if the error goes away.

Regardless of the underlying root cause, one solution you could try is to modify your WQL query to include the name of the printer you're looking for. By having WMI do the enumeration instead of you, it might bypass the problematic items.

SelectQuery q = new SelectQuery(
    "select caption from win32_printer where Caption='Fax' ");
bool found = new System.Management.ManagementObjectSearcher(q).Get().Count > 0;

If that doesn't work, then put your comparison of Caption into an exception handler, and ignore printers that throw exceptions.

Of course, if the underlying problem is that you're trying to find printers that you don't have permissions to look at, then you'll need to adjust your application so that it's running with elevated permissions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM