Finding downloads folder programmatically (Go)

62 views Asked by At

I'm trying to find a platform agnostic way to determine the user's downloads folder. I'm using golang's fyne. So far, I've found a few helpful functions, but can't seem to tie it together. More importantly, I'm not sure what issues can come up for different platforms.

  • os.Getwd() gets the name of a working directory
  • filepath.Dir() goes back one step and gets the filepath
  • strings.Contains("filepath","downloads") will tell me if a filepath has "downloads" in it

Naively, I could probably do something like this:

path,_ := os.Getwd()

//count how far back 
steps_back := -1
for strings.Contains(path,"downloads") { // runs as long as path has "downloads" in it

path = filepath.Dir(path) 
steps_back++
}

downloads_path,_ := os.Getwd()

for step=0;step<steps_back;step++ {
downloads_path = filepath.Dir(downloads_path)
}

But:

  1. This only works if the user is running the application from some extension of their downloads folder
  2. I have no clue if there are platform-specific roadblocks

Any ideas?

1

There are 1 answers

0
Kris On

I would try to use the os.UserHomeDir() function along with looking for Downloads under it. It probably won't work for every case, and users are probably able to customize their default download directory to some extent, but it may be good enough for what you need to do.

package main

import (
    "fmt"
    "log"
    "os"
)

var (
    DownloadDirNames []string = []string{"Downloads", "downloads", "download", "Downloads", "etc..."}
)

func main() {
    var downloadDir string

    homeDir, err := os.UserHomeDir()
    if err != nil {
        log.Fatal(err)
    }

    for _, ddn := range DownloadDirNames {
        var dir = filepath.Join(homeDir, ddn)

        if _, err := os.Stat(dir); os.IsNotExist(err) {
            fmt.Println(dir, "does not exist")
        } else {
            fmt.Println("The provided directory named", dir, "exists")
            downloadDir = dir
            break
        }
    }
    fmt.Println("Download Directory:", downloadDir)
}

Output:

# go run cmd/test_proj/main.go
Hello World
/home/<user_name>/Downloads does not exist
/home/<user_name>/downloads does not exist
The provided directory named /home/<user_name>/download exists
Download Directory: /home/<user_name>/download
#