Windows服务usb弹出?

时间:2012-05-14 19:49:13

标签: c# windows windows-services

我正在尝试调整以下项目http://www.codeproject.com/Articles/32026/Capturing-Device-Events-in-a-C-Windows-Service以检测USB磁盘并将其弹出或根据标识字符串停止安装。 首先,当到达这部分代码时,项目无法正确运行:  if(hdr.dbcc_devicetype == Win32.DBT_DEVTYP_DEVICEINTERFACE)                         {

                        Win32.DEV_BROADCAST_DEVICEINTERFACE deviceInterface;
                        deviceInterface = (Win32.DEV_BROADCAST_DEVICEINTERFACE)
                            Marshal.PtrToStructure(eventData, typeof(Win32.DEV_BROADCAST_DEVICEINTERFACE));

                        string name = new string(deviceInterface.dbcc_name);

                        name = name.Substring(0, name.IndexOf('\0')) + "\\";
                        StringBuilder stringBuilder = new StringBuilder();

                        Win32.GetVolumeNameForVolumeMountPoint(name, stringBuilder, 100);

                        uint stringReturnLength = 0;
                        string driveLetter = "";

                        Win32.GetVolumePathNamesForVolumeNameW(stringBuilder.ToString(), driveLetter, (uint) driveLetter.Length, ref stringReturnLength);



                        if (stringReturnLength == 0)
                        {
                            // TODO handle error
                        }

                        driveLetter = new string(new char[stringReturnLength]);

                        if (!Win32.GetVolumePathNamesForVolumeNameW(stringBuilder.ToString(), driveLetter, stringReturnLength, ref stringReturnLength))
                        {
                            //// TODO handle error
                        }
                        RegisterForHandle(driveLetter[0]);

...} 它从不获取驱动器号,driveLetter字符串始终为空。 stringBuilder =ôu<¬ë6,名称变量= = \?\ USBSTOR #Disk& Ven_& Prod_USB_DISK_2.0& Rev_PMAP#07A512076EB115FA& 0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b} \

它出了什么问题?或者关于我正在尝试做什么的任何想法?

2 个答案:

答案 0 :(得分:1)

我用这个新的逻辑改变了现有的逻辑...这已经过测试并且对我有用..

writeLog("Device valid");

try
{
    Win32.DEV_BROADCAST_DEVICEINTERFACE deviceInterface;
    deviceInterface = (Win32.DEV_BROADCAST_DEVICEINTERFACE)
        Marshal.PtrToStructure(eventData, typeof(Win32.DEV_BROADCAST_DEVICEINTERFACE));


    foreach (ManagementObject drive in
            new ManagementObjectSearcher(
                "select DeviceID, Model from Win32_DiskDrive where InterfaceType='USB'").Get())
    {
        // associate physical disks with partitions
        ManagementObject partition = new ManagementObjectSearcher(String.Format(
            "associators of {{Win32_DiskDrive.DeviceID='{0}'}} where AssocClass = Win32_DiskDriveToDiskPartition",
            drive["DeviceID"])).First();

        if (partition != null)
        {
            // associate partitions with logical disks (drive letter volumes)
            ManagementObject logical = new ManagementObjectSearcher(String.Format(
                "associators of {{Win32_DiskPartition.DeviceID='{0}'}} where AssocClass = Win32_LogicalDiskToPartition",
                partition["DeviceID"])).First();

            if (logical != null)
            {
                // finally find the logical disk entry to determine the volume name
                ManagementObject volume = new ManagementObjectSearcher(String.Format(
                    "select FreeSpace, Size, VolumeName from Win32_LogicalDisk where Name='{0}'",
                    logical["Name"])).First();

                string capacity = bytesToUnit((ulong)volume["Size"]);
                string freeSpace = bytesToUnit((ulong)volume["FreeSpace"]);

                writeLog("Drive Letter    "     + logical["Name"].ToString() + Environment.NewLine +
                         "Drive Name    "       + volume["VolumeName"].ToString() + Environment.NewLine +
                         "Drive Capacity    "   + capacity + Environment.NewLine +
                         "Drive Free Space    " + freeSpace);
            }
        }
    }
}
catch (Exception exp)
{
    writeLog("Exception: " + exp.ToString());
}

private string bytesToUnit(ulong bytes)
{
    string[] Suffix = { "B", "KB", "MB", "GB", "TB" };
    int i = 0;
    double dblSByte = bytes;

    if (bytes > 1024)
    {
        for (i = 0; (bytes / 1024) > 0; i++, bytes /= 1024)
        {
            dblSByte = bytes / 1024.0;
        }
    }
    return String.Format("{0:0.##}{1}", dblSByte, Suffix[i]);
}

public void writeLog(string log)
{
    eventLog1.WriteEntry(log);
}

<强> GetResult.cs

public static class GetResult
    {
        public static ManagementObject First(this ManagementObjectSearcher searcher)
        {
            ManagementObject result = null;
            foreach (ManagementObject item in searcher.Get())
            {
                result = item;
                break;
            }
            return result;
        }
    }

它将为您提供您可能需要的所有细节。

希望这会对你有帮助......

答案 1 :(得分:0)

要枚举驱动器使用:

IEnumerable<DriveInfo> allDrives = DriveInfo.GetDrives().Where(c => c.DriveType == DriveType.Removable); 

但我不知道如何删除它