First, this code worked in VS2005.
The code in VS2008 crashes with an UnauthorizedAccessException whenever I try stepping over the foreach loop and assign a ManagementObject.
public static List<string> GetPrintersCollection() {
if (printers == null) {
printers = new List<string>();
string searchQuery = "SELECT * FROM Win32_Printer";
try {
using (ManagementObjectSearcher searchPrinters = new ManagementObjectSearcher(searchQuery)) {
ManagementObjectCollection Printers = searchPrinters.Get(); // <= Printers data below
foreach (ManagementObject printer in Printers) { // <= Error Here
printers.Add(printer.Properties["Name"].Value.ToString());
}
}
} catch (UnauthorizedAccessException err) {
Console.WriteLine(err.Message); // the message is an empty string
throw new Exception("PrinterSpool - GetPrintersCollection: You do not have authorization to access this printer.");
} catch (Exception err) {
throw new Exception(string.Format("PrinterSpool - GetPrintersCollection: {0}", err.Message));
}
}
return printers;
}
StackTrace =
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()
at AcpClasses.PrinterSpool.GetPrintersCollection()…
When I try to view the data in the Locals window, these fields look immediately suspect:
1. Count – Value: “Function evaluation timed out.”
2. IsSynchronized – Value: Function evaluation disabled because a previous function evaluation timed out.
3. SyncRoot – Value: Function evaluation disabled because a previous function evaluation timed out.
How can I try to debug this further to find out what is going on?
To debug further you need to inspect
Printersbefore entering the foreach loop.searchPrinters.Get()line.Another thing that should help is changing
err.Messagetoerr.ToString().For what it’s worth, I debugged this with no problems running both VS 2005 & 2008 on XP.
EDIT: Posting code for you to try.
EDIT: The only other thing I can think of is to manually go through your Printers and Faxes to see if any are causing problems for you.