首先,此代码在VS2005中工作。Win32_Printer ManagementObjectSearcher错误(VS2008 C#)
无论何时尝试跨越foreach循环并分配ManagementObject时,VS2008中的代码都会崩溃并伴随UnauthorizedAccessException。
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;
}
堆栈跟踪=
在System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(的Int32的errorCode,IntPtr的errorInfo中)
在System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()
在AcpClasses.PrinterSpool.GetPrintersCollection ()...
当我尝试查看本地窗口中的数据时,这些字段看起来立即可疑:
1.计数 - 值:“功能评估超时。
2. IsSynchronized - 值:功能评估由于先前的功能评估超时而被禁用。
3. SyncRoot - 值:功能评估被禁用,因为之前的功能评估超时。
我该如何尝试进一步调试以找出发生了什么?
评论: 其他地方定义为列表 printers = null; 此代码也不再适用于Visual Studio 2005(我刚刚查询了仅查询Win32_Printer的控制台应用程序)。 –
jp2code
2009-10-05 15:20:13
我在回答中添加了一些代码,可以帮助诊断您的问题。 – 2009-10-05 19:54:15