如何在Google Golang中获取Windows系统的根目录?

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

How to get system root directory for Windows in Google Golang?

问题

在Go语言中,可以使用os.Getenv("SystemRoot")来获取Windows系统的根目录。这个环境变量会返回类似于C:\Windows的路径。

英文:

Under Windows, the system root directory could be like C:// or D:// (when the OS is installed in driver D:/). How to get this folder in Go?

答案1

得分: 4

你可以使用filepath.VolumeName(os.GetEnv("SYSTEMROOT")) + "\\"或更简短的os.GetEnv("SYSTEMDRIVE") + "\\"。实际上,windir环境变量可能不再应该使用,因为它不是一个由系统控制的环境变量。

提到的环境变量的来源

英文:

You could use filepath.VolumeName(os.GetEnv("SYSTEMROOT")) + "\\" or the shorter os.GetEnv("SYSTEMDRIVE") + "\\". The windir environment variable probably shouldn't be used anymore honestly since it is not a system-controlled environment variable.

Source for the mentioned environment variables

答案2

得分: 1

你可以使用os.Getenv来获取"environment"变量windir的值。下面是一个示例:

package main
import "os"
import "fmt"

func main() {
    fmt.Println("系统目录:", os.Getenv("windir"))
}

这段代码将打印出系统目录的值。

英文:

You may use os.Getenv to get the value for "environment" variable windir. An example is below:

package main
import "os"
import "fmt"


func main() {

    fmt.Println("system dir: ", os.Getenv("windir"))
    
}

答案3

得分: 0

以下是与Windows或Unix兼容的一些选项。

import "os"

func root() string {
   return os.Getenv("SystemDrive") + string(os.PathSeparator)
}
import (
   "os"
   "path/filepath"
)

func root() string {
   s := os.TempDir()
   return filepath.Join(s, "..", "..")
}
import (
   "os"
   "strings"
)

func root() string {
   s := os.TempDir()
   return s[:strings.IndexRune(s, os.PathSeparator) + 1]
}
import (
   "os"
   "path/filepath"
)

func root() string {
   s := os.TempDir()
   return filepath.VolumeName(s) + string(os.PathSeparator)
}
import (
   "os"
   "strings"
)

func root() string {
   s := os.TempDir()
   return strings.SplitAfterN(s, string(os.PathSeparator), 2)[0]
}
英文:

Here are some options that work with Windows or Unix.

import "os"

func root() string {
   return os.Getenv("SystemDrive") + string(os.PathSeparator)
}
import (
   "os"
   "path/filepath"
)

func root() string {
   s := os.TempDir()
   return filepath.Join(s, "..", "..")
}
import (
   "os"
   "strings"
)

func root() string {
   s := os.TempDir()
   return s[:strings.IndexRune(s, os.PathSeparator) + 1]
}
import (
   "os"
   "path/filepath"
)

func root() string {
   s := os.TempDir()
   return filepath.VolumeName(s) + string(os.PathSeparator)
}
import (
   "os"
   "strings"
)

func root() string {
   s := os.TempDir()
   return strings.SplitAfterN(s, string(os.PathSeparator), 2)[0]
}

huangapple
  • 本文由 发表于 2016年12月21日 11:07:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/41254463.html
匿名

发表评论

匿名网友

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

确定