使用Go语言在Windows资源管理器中显示文件?

huangapple go评论86阅读模式
英文:

Show file in Windows Explorer using Go?

问题

如何使用Go在Windows资源管理器中显示文件?

这个命令在命令行中可以正常工作:

explorer /select,C:\data\My File.txt

但是,无论尝试什么参数组合,我都无法使用Go的exec.Command()方法实现相同的命令。

这个可以工作:

exec.Command(`explorer`, `/select,C:\data\MyFile.txt`) // 成功

但是,如果文件名中有空格,则会失败。

exec.Command(`explorer`, `/select,C:\data\My File.txt`) // 失败

注意:

英文:

How do you show a file in windows explorer using Go?

This command works as expected from the command line:

explorer /select,C:\data\My File.txt

I can't get the same command to work using Go's exec.Command() method, no matter what combination of arguments tried.

This works:

exec.Command(`explorer`, `/select,C:\data\MyFile.txt`) // SUCCEEDS 

but fails with a space in the filename.

exec.Command(`explorer`, `/select,C:\data\My File.txt`) // FAILS 

Notes:

答案1

得分: 7

你可以将/select,操作和实际路径分开,并将它们作为单独的参数传递,这样就可以使其正常工作:

exec.Command(`explorer`, `/select,`, `C:\data\My File.txt`)
英文:

You can get it to work if you separate the /select, action and the actual path, and you pass them as separate parameters:

exec.Command(`explorer`, `/select,`, `C:\data\My File.txt`)

答案2

得分: 7

一个更完整的答案适用于Go语言新手(就像我自己一样):

package main
import (
    "os/exec"
)

func main() {
    cmd := exec.Command(`explorer`, `/select,`, `C:\data\My File.txt`)
    cmd.Run()
}

这段代码使用Go语言编写,它通过os/exec包调用系统命令来打开资源管理器并选中指定的文件(在这个例子中是C:\data\My File.txt)。

英文:

A more complete answer for the golang newbies (like myself):

package main
import (
    "os/exec"
)

func main() {
    cmd := exec.Command(`explorer`, `/select,`, `C:\data\My File.txt`)
    cmd.Run()
}

huangapple
  • 本文由 发表于 2015年8月24日 10:55:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/32173871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定