当然可以根据盘符来获取设备属性中的 “父系” 值。以下是相应的代码示例:
package main
import (
"fmt"
"golang.org/x/sys/windows"
"strings"
)
func main() {
driveLetter := "E:" // 替换为你要查询的盘符
volumePath, err := getVolumePath(driveLetter)
if err != nil {
fmt.Printf("Failed to get volume path: %v\n", err)
return
}
devicePath, err := getDevicePath(volumePath)
if err != nil {
fmt.Printf("Failed to get device path: %v\n", err)
return
}
parentValue, err := getParentPropertyValue(devicePath)
if err != nil {
fmt.Printf("Failed to get parent property value: %v\n", err)
return
}
fmt.Println("父系属性值:", parentValue)
}
func getVolumePath(driveLetter string) (string, error) {
var buf [windows.MAX_PATH]uint16
err := windows.GetVolumePathNamesForVolumeName(
windows.StringToUTF16Ptr(driveLetter+"\\"),
&buf[0],
uint32(len(buf)),
nil,
)
if err != nil {
return "", fmt.Errorf("failed to get volume path for drive %s: %w", driveLetter, err)
}
paths := windows.UTF16ToString(buf[:])
return strings.Split(paths, "\000")[0], nil
}
func getDevicePath(volumePath string) (string, error) {
var buf [windows.MAX_PATH]uint16
err := windows.QueryDosDevice(
windows.StringToUTF16Ptr(volumePath),
&buf[0],
uint32(len(buf)),
)
if err != nil {
return "", fmt.Errorf("failed to query device path for volume %s: %w", volumePath, err)
}
return windows.UTF16ToString(buf[:]), nil
}
func getParentPropertyValue(devicePath string) (string, error) {
deviceHandle, err := windows.CreateFile(
windows.StringToUTF16Ptr(devicePath),
windows.GENERIC_READ,
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE,
nil,
windows.OPEN_EXISTING,
0,
0,
)
if err != nil {
return "", fmt.Errorf("failed to open device: %w", err)
}
defer windows.CloseHandle(deviceHandle)
const propertyBufferSize = 1024
var propertyBuffer [propertyBufferSize]byte
propertyKey := &windows.DevPropKey{
FormatID: windows.DEVPROP_TYPE_STRING_LIST,
PropertyID: 10, // 对应父系属性编号(可根据实际情况修改)
}
_, err = windows.DeviceIoControl(
deviceHandle,
&windows.IoctlStorageQueryProperty,
(*byte)(unsafe.Pointer(propertyKey)),
uint32(unsafe.Sizeof(*propertyKey)),
&propertyBuffer[0],
propertyBufferSize,
nil,
nil,
)
if err != nil {
return "", fmt.Errorf("failed to query property: %w", err)
}
propertyData := (*windows.DevPropStringList)(&propertyBuffer[0])
parentValue := propertyData.Strings[0] // 父系属性的第一个值
return parentValue, nil
}
请将 driveLetter
替换为你要查询的盘符,并根据实际情况修改父系属性编号。此示例代码会获取指定盘符的卷路径,然后根据卷路径查询设备路径,并获取设备属性中的 “父系” 值。请注意,在 Windows 上运行该代码需要具有管理员权限。
内容由零声教学AI助手提供,问题来源于学员提问