Way to know if two partitions are in one physical hard disk without WMI?

后端 未结 2 1963
南笙
南笙 2021-01-13 18:02

I have those partitions (in Windows) for example:

Hard Disk 1 - Partition C, Partition D
Hard Disk 2 - Partition E

Is there any way in a pr

2条回答
  •  日久生厌
    2021-01-13 18:23

    I don't know of any other managed way to get disk partition information. You may use the Win32 API using P/Invoke from C#. However, you shouldn't unless it's absolutely necessary.

    The Win32 function you'll need is called DeviceIoControl(). The API documentation can be found at http://msdn.microsoft.com/en-us/library/aa363216(VS.85).aspx. Call DeviceIoControl() with the control code IOCTL_STORAGE_GET_DEVICE_NUMBER and you'll get the physical disk drive for the given partition device handle. The device handle for the partition can be retrieved using CreateFile() API.

    However, using DeviceIoControl() is cumbersome and you will most likely have to make different versions for the 32-bit and 64-bit versions of Windows.

    To retrieve all partitions you may use the managed code System.IO.DriveInfo like this:

    var x = from di in DriveInfo.GetDrives()
            where (di.DriveType == DriveType.Fixed)
            select di;
    
    foreach (DriveInfo di in x)
    {
        // Call DeviceIoControl() using the partition name from di.Name and the IOCTL_STORAGE_GET_DEVICE_NUMBER  control code to retrieve the physical disk
    }
    

    It seems pinvoke.net has some signatures for C#.

提交回复
热议问题