How to resolve user environment variables in filepath


April 2019


41 time


Golang on windows. Trying to use


Getting file path not found and golang is not resolving %userprofile% to my C:\users\myusername folder.

3 answers


Have a look at

You can read the 'userprofile' environment value and and build the path before passing it to os.Open


To get a file handle, and make your program a little portable too, try

userprofile := os.Getenv("USERPROFILE")
f, err := os.Open(path.Join(userprofile, "myfile.txt"))

The os.Getenv() will read the environment variable and path.Join() will take care of properly constructing the path (so no need to do \\).

Instead of os.Getenv() you might also want to look at os.LookupEnv(). This will tell you if the environment variable you're looking for is empty or simply not existing. A good example of how you can use that to set default values can be found in this answer on SO.

userprofile := os.Getenv("USERPROFILE")