Go 獲取已插入 U 盤碟符

pibigstar發表於2019-09-22
package main

import (
    "fmt"
    "strconv"
    "syscall"

    "golang.org/x/sys/windows/registry"
)

// 獲取系統中所有碟符
func GetSystemDisks() []string {
    // 獲取系統dll
    kernel32 := syscall.MustLoadDLL("kernel32.dll")
    // 獲取dll中函式
    GetLogicalDrives := kernel32.MustFindProc("GetLogicalDrives")
    // 呼叫dll中函式
    n, _, _ := GetLogicalDrives.Call()
    s := strconv.FormatInt(int64(n), 2)
    var allDrives = []string{"A:", "B:", "C:", "D:", "E:", "F:", "G:", "H:",
        "I:", "J:", "K:", "L:", "M:", "N:", "O:", "P:", "Q:", "R:", "S:", "T:",
        "U:", "V:", "W:", "X:", "Y:", "Z:"}
    temp := allDrives[0:len(s)]
    var d []string
    for i, v := range s {
        if v == 49 {
            l := len(s) - i - 1
            d = append(d, temp[l])
        }
    }
    var drives []string
    for i, v := range d {
        drives = append(drives[i:], append([]string{v}, drives[:i]...)...)
    }
    return drives
}

// 獲取插入的U盤碟符
func GetUDisk() []string {
    //查詢登錄檔,判斷是否插入U盤
    k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Services\USBSTOR\Enum`, registry.QUERY_VALUE)
    if err != nil {
        fmt.Println("Not have U-Disk")
        return nil
    }
    defer k.Close()
    // 獲取登錄檔中值,得到插入了幾個U盤
    count, _, err := k.GetIntegerValue("Count")
    // 獲取全部碟符
    disks := GetSystemDisks()

    return disks[len(disks)-int(count):]
}

更詳細的程式碼可參考:https://github.com/pibigstar/go-demo 裡面包含了 Go 常用的設計模式、Go 面試易錯點、簡單的小專案(區塊鏈,爬蟲等)、還有各種第三方的對接(redis、sms、nsq、elsticsearch、alipay、oss...),如果對你有所幫助,請給個 Star,你的支援,是我最大的動力!

相關文章