簡體   English   中英

Windows服務USB彈出?

[英]Windows service usb eject?

我正在嘗試修改以下項目http://www.codeproject.com/Articles/32026/Capturing-Device-Events-in-aC-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} \\

它出什么問題了? 或關於我要做什么的任何想法?

我已經用這個新邏輯改變了現有的邏輯。

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;
        }
    }

它會為您提供您可能需要的所有詳細信息。

希望這個能對您有所幫助...

要枚舉驅動器,請使用:

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

但我不知道如何刪除它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM