关于SetupDiEnumDeviceInfo枚举设备返回 缓冲区无效 解决办法

来源:互联网 发布:openstack云计算入门 编辑:程序博客网 时间:2024/05/16 18:46

现象:我的程序中有个功能是要枚举设备。代码如下, 在XP 32位系统下运行没有问题,到Win7 64位系统时则不能枚举。调试发现SetupDiEnumDeviceInfo返回false。

    public static List<string> GetDeviceProperty(string portname)             {                 List<string> HWList = new List<string>();                 try                 {                     Guid myGUID = System.Guid.Empty;                     IntPtr hDevInfo = SetupDiGetClassDevs(ref myGUID, 0, IntPtr.Zero, DIGCF_ALLCLASSES | DIGCF_PRESENT);                     if (hDevInfo.ToInt32() == INVALID_HANDLE_VALUE)                     {                         throw new Exception("Invalid Handle");                     }                     SP_DEVINFO_DATA DeviceInfoData;                     DeviceInfoData = new SP_DEVINFO_DATA();                     DeviceInfoData.cbSize = 28;                     DeviceInfoData.devInst = 0;                     DeviceInfoData.classGuid = System.Guid.Empty;                     DeviceInfoData.reserved = 0;                     UInt32 i;                     StringBuilder property = new StringBuilder("");                     property.Capacity = MAX_DEV_LEN;                     for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, DeviceInfoData); i++)                     {                         SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, (uint)SPDRP_CLASS, 0, property, (uint)property.Capacity, IntPtr.Zero);                         if (property.ToString().ToLower() != "ports")                         {                             continue;                         }                         SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, (uint)SPDRP_FRIENDLYNAME, 0, property, (uint)property.Capacity, IntPtr.Zero);                                     if (!property.ToString().ToLower().Contains(portname.ToLower()))                             continue;//找到对应于portname的设备                         string port = property.ToString().Trim().Substring(property.ToString().IndexOf("("));                         port = port.Replace("(", "").Replace(")", "");                         HWList.Add(port);                         break;                     }                     Console.Write(Marshal.GetLastWin32Error().ToString());                                     SetupDiDestroyDeviceInfoList(hDevInfo);                 }                 catch (Exception ex)                 {                     throw new Exception("枚举设备列表出错", ex);                 }                 return HWList;             }  

分析原因: 是32位和64位系统差异造成。

解决办法:判断是否为64位系统。

    if (Environment.Is64BitOperatingSystem)          DeviceInfoData.cbSize = 32;//(16,4,4,4)      else          DeviceInfoData.cbSize = 28;  
转:http://blog.csdn.net/ypoflyer/article/details/17224841


0 0