Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a registry key/string with Go

Tags:

go

registry

I was following this document to create a key/string in windows registry with this code snippet:

package main

import (
    "golang.org/x/sys/windows/registry"
    "log"
)

func main() {

    k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Audio`, registry.QUERY_VALUE)
    if err != nil {
        log.Fatal(err)
    }
    k.SetStringValue("xyz", "blahblah")
    err = k.Close()
    if err != nil {
        log.Fatal(err)
    }
}

but nothing happens, without any errors. Edit (clarification): It doesn't work, in any circumstances.

like image 291
Ted Kaczynski Avatar asked Sep 01 '25 16:09

Ted Kaczynski


1 Answers

You are opening the key with only the QUERY_VALUE permission, but you also need SET_VALUE in order to successfully call SetStringValue.

You should also be checking the return value on SetStringValue, which would have likely informed you what the problem was.

k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Audio`, registry.QUERY_VALUE|registry.SET_VALUE)
if err != nil {
    log.Fatal(err)
}
if err := k.SetStringValue("xyz", "blahblah"); err != nil {
    log.Fatal(err)
}
if err := k.Close(); err != nil {
    log.Fatal(err)
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!