I can open a explorer window using on Windows 10 cmd
explorer C:\Users\bruce\Downloads\
So I'm thinking executing this command in go, but it opens Documents
folder instead of Downloads
folder, how can I solve this issue
package main
import (
"fmt"
"os"
"os/exec"
"runtime"
)
func main() {
homeDir, _ := os.UserHomeDir()
if runtime.GOOS == "darwin" {
downloadDir := homeDir "/Downloads/"
cmd := `open "` downloadDir `"`
exec.Command("/bin/bash", "-c", cmd).Output()
} else {
downloadDir := homeDir "\\Downloads\\"
cmd := `explorer ` downloadDir
fmt.Println("cmd: ", cmd)
exec.Command("cmd", "/C", cmd).Output()
}
}
CodePudding user response:
Problem solved, turns out that the first parameter of exec.Command()
should use explorer
instead of cmd
The snippet below is working
package main
import (
"os"
"os/exec"
"runtime"
"strings"
)
func main() {
homeDir, _ := os.UserHomeDir()
downloadDir := homeDir "/Downloads/"
if runtime.GOOS == "darwin" {
cmd := `open "` downloadDir `"`
exec.Command("/bin/bash", "-c", cmd).Start()
} else {
downloadDir = strings.ReplaceAll(downloadDir, "/", "\\")
exec.Command("explorer", downloadDir).Start()
}
}
Edit
More simplified version, use downloadDir := filepath.Join(homeDir, "Downloads")
instead of downloadDir = strings.ReplaceAll(downloadDir, "/", "\\")
package main
import (
"os"
"os/exec"
"path/filepath"
"runtime"
)
func main() {
homeDir, _ := os.UserHomeDir()
downloadDir := filepath.Join(homeDir, "Downloads")
if runtime.GOOS == "darwin" {
exec.Command("open", downloadDir).Start()
} else {
exec.Command("explorer", downloadDir).Start()
}
}
Edit2
package main
import (
"os"
"os/exec"
"path/filepath"
"runtime"
)
func main() {
homeDir, _ := os.UserHomeDir()
downloadDir := filepath.Join(homeDir, "Downloads")
cmd := "open"
if runtime.GOOS == "windows" {
cmd = "explorer"
}
exec.Command(cmd, downloadDir).Start()
}
CodePudding user response:
[for window]
I recommend using a specific folder instead of joining the path by yourself,
because when you install the application on a custom download path, your application will be run with the wrong condition.
a specific folder is a standard folder that was registered with the system and this one is on XP or higher version of window
for manual, you can use like this
win r -> shell:{specific folder}
example
win r -> shell:downloads
for golang you can use like this
err := exec.Command("explorer", "shell:downloads").Start()
if err != nil {
log.Fatalln(err.Error())
}
for more information https://gist.github.com/gabe31415/ac22a4f5c874ee33ab0083fdb4e24e66