-
Notifications
You must be signed in to change notification settings - Fork 100
/
profile.go
77 lines (66 loc) · 2.55 KB
/
profile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//go:build windows && amd64
// +build windows,amd64
package winapi
import (
"syscall"
"unsafe"
)
var (
modUserenv = syscall.NewLazyDLL("Userenv.dll")
procGetDefaultUserProfileDirectoryW = modUserenv.NewProc("GetDefaultUserProfileDirectoryW")
procGetProfilesDirectoryW = modUserenv.NewProc("GetProfilesDirectoryW")
)
// GetDefaultUserProfileDirectory returns the path to the directory in which the
// default user's profile is stored.
//
// See: https://docs.microsoft.com/en-us/windows/desktop/api/userenv/nf-userenv-getdefaultuserprofiledirectoryw
func GetDefaultUserProfileDirectory() (string, error) {
var bufferSize uint32
r1, _, err := procGetDefaultUserProfileDirectoryW.Call(
uintptr(0), // lpProfileDir = NULL,
uintptr(unsafe.Pointer(&bufferSize)), // lpcchSize = &bufferSize
)
// The first call always "fails" due to the buffer being NULL, but it should
// have stored the needed buffer size in the variable bufferSize.
// Sanity check to make sure bufferSize is sane.
if bufferSize == 0 {
return "", err
}
// bufferSize now contains the size of the buffer needed to contain the path.
buffer := make([]uint16, bufferSize)
r1, _, err = procGetDefaultUserProfileDirectoryW.Call(
uintptr(unsafe.Pointer(&buffer[0])), // lpProfileDir = &buffer
uintptr(unsafe.Pointer(&bufferSize)), // lpcchSize = &bufferSize
)
if r1 == 0 {
return "", err
}
return syscall.UTF16ToString(buffer), nil
}
// GetProfilesDirectory returns the path to the directory in which user profiles
// are stored. Profiles for new users are stored in subdirectories.
//
// See: https://docs.microsoft.com/en-us/windows/desktop/api/userenv/nf-userenv-getprofilesdirectoryw
func GetProfilesDirectory() (string, error) {
var bufferSize uint32
r1, _, err := procGetProfilesDirectoryW.Call(
uintptr(0), // lpProfileDir = NULL,
uintptr(unsafe.Pointer(&bufferSize)), // lpcchSize = &bufferSize
)
// The first call always "fails" due to the buffer being NULL, but it should
// have stored the needed buffer size in the variable bufferSize.
// Sanity check to make sure bufferSize is sane.
if bufferSize == 0 {
return "", err
}
// bufferSize now contains the size of the buffer needed to contain the path.
buffer := make([]uint16, bufferSize)
r1, _, err = procGetProfilesDirectoryW.Call(
uintptr(unsafe.Pointer(&buffer[0])), // lpProfileDir = &buffer
uintptr(unsafe.Pointer(&bufferSize)), // lpcchSize = &bufferSize
)
if r1 == 0 {
return "", err
}
return syscall.UTF16ToString(buffer), nil
}