在Golang中打开可执行文件、图像、视频和文本文件。

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

Open Executable;image;video;text file in Golang

问题

嘿,我正在尝试使用Golang运行不同的东西,从图像到文本文件。
注意!我不是要显示它们,而是要打开它们!
就像在命令提示符中使用start filePath.txt打开普通文本文件一样。

我尝试了很多方法,但没有一个有效。
唯一有效的方法是使用可执行文件,而且它不是独立打开,而是附加到我的当前程序,这意味着所有输出都会显示在同一个控制台中。

这是我的当前代码(没有做任何事情):

func UpdateProject(downloadString string) {
   var linkData = strings.Split(downloadString, "/")
   var fileName = linkData[len(linkData)-1]
   f, _ := os.Create(fileName)
   defer f.Close()
   resp, _ := http.Get(downloadString)
   body, _ := ioutil.ReadAll(resp.Body)
   f.WriteString(string(body))
   exec.Command("cmd", "start", fileName).Run()
}

希望能得到一些帮助,并强调我只想像在Windows上双击文件时那样打开文件。
提前感谢!

英文:

Edit : Only aiming Windows

Hey i am trying to run different stuff with Golang, from images to text files
Carrefull ! I am not trying to display them but open them !
Like openning a regular text file like cmd would do with start filePath.txt would open in world.

I tried MANY methods but none of them worked.
The only one that worked was with an executable, and instead of opening independently, it was attached to my current program, meaning all output where show in the same current console.

here is my current (not doing anything code)

func UpdateProject(downloadString  string) {
   var linkData = strings.Split(downloadString, "/")
   var fileName = linkData[len(linkData)-1]
   f, _ := os.Create(fileName)
   defer f.Close()
   resp, _ := http.Get(downloadString)
   body, _ := ioutil.ReadAll(resp.Body)
   f.WriteString(string(body))
   exec.Command("cmd", "start", fileName).Run()
}

I hope getting some help and insist on the fact that i just want to open the file like windows would when double clicking on it.
Thanks by advance !

答案1

得分: 0

如果找到了解决方案,可以使用以下代码:

execFPath, _ := os.Executable()
execPath := filepath.Dir(execFPath)

var sI syscall.StartupInfo
var pI syscall.ProcessInformation
argv := syscall.StringToUTF16Ptr(os.Getenv("windir")+"\\system32\\cmd.exe /C "+ fmt.Sprintf("\"%s\\%s\"", execPath, "MyFile.png"))
syscall.CreateProcess(nil,argv,nil,nil,true,0,nil,nil,&sI,&pI)

CreateProcess函数启动一个带有参数的cmd命令,例如"xxxx.jpg",在cmd中执行的意思是在可执行文件、图像和其他内容上工作。

英文:

If found the solution with digging

execFPath, _ := os.Executable()
execPath := filepath.Dir(execFPath)

var sI syscall.StartupInfo
var pI syscall.ProcessInformation
argv := syscall.StringToUTF16Ptr(os.Getenv("windir")+"\\system32\\cmd.exe /C "+ fmt.Sprintf("\"%s\\%s\"", execPath, "MyFile.png"))
syscall.CreateProcess(nil,argv,nil,nil,true,0,nil,nil,&sI,&pI)

CreateProcesss tart a cmd with argument like "xxxx.jpg", with in cmd mean execute, work on executable, images & stuff

huangapple
  • 本文由 发表于 2021年9月12日 04:07:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/69146358.html
匿名

发表评论

匿名网友

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

确定