I want to open the file contain two spaces with explorer from Go's exec.Command()
.
This command works as expected from Windows PowerShell.
Explorer "file://C:\Users\1. Sample\2. Sample2"
And Using Go's exec.Command()
works with fileName contain space like this.
exec.Command(`explorer`, "file://C:\Users\1. Sample").CombinedOutput()
But failed with fileName contain two spaces like this
exec.Command(`explorer`, "file://C:\Users\1. Sample\2. Sample2").CombinedOutput()
Please tell me how to solve this.
This code works as expected. Thanks.
exec.Command(`explorer`, `file://C:\Users\1. Sample\2. Sample2`).CombinedOutput()
But actual input is string(not raw string literal) as below. So I think that I need to convert string to raw string.
url := "file://C:\Users\1. Sample\2. Sample2"
<I need to convert to raw string literal?>
result, err := exec.Command(`explorer`, url).CombinedOutput()
if err != nil {
log.Fatal(err)
}
Having 2 spaces in file names has nothing to do with failing to run the command.
You are using interpreted string literals:
"file://C:\Users\1. Sample\2. Sample2"
In interpreted string literals the backslash character \
is special and if you want your string
to have a backslash, you have to escape it, and the escape sequence is 2 backslahses: \\
:
"file://C:\\Users\\1. Sample\\2. Sample2"
Or even better: use raw string literals (and then you don't need to escape it):
`file://C:\Users\1. Sample\2. Sample2`
That weird 2
character in your file name may also cause an issue. If you include that in Go source code, it will be interpreted and encoded as UTF-8 string. You pass this as a parameter, but your OS (windows) may use a different character encoding when checking file names, so it may not find it. Remove that weird 2
character from the file name if correcting the string literal is not sufficient to make it work.
When you run the command from PowerShell, it works because PowerShell does not expect an interpreted string and it uses the encoding that is also used to store file names.
Also Cmd.CombinedOutput()
(just like Cmd.Run()
and Cmd.Start()
) returns an error
, be sure to check that as it may provide additional info.