4

I'm trying to read the target file/directory of a shortcut (.lnk) file using Go.

I already have a loop for all the files in a directory and I can successfully identify if it is a dir with IsDir() or if it is a file IsRegular(). Now I need a way to read if it is a link and, if it is a .lnk, the path of it so I can print it.

I couldn't find any way of doing this and I've been searching on SO but nothing comes up. Any idea?

Emi
  • 525
  • 1
  • 3
  • 21

1 Answers1

4

You need to read the lnk binary format as defined by Microsoft

In Go, its structure would translate to (as used in the exponential-decay/shortcuts)

//structs that make up the shortcut specification [76 bytes] 
type ShellLinkHeader struct {
   HeaderSize  [4]byte           //HeaderSize
   ClassID     [16]byte          //LinkCLSID
   LinkFlags   uint32            //LinkFlags      [4]byte
   FileAttr    uint32            //FileAttributes [4]byte
   Creation    [8]byte           //CreationTime
   Access      [8]byte           //AccessTime
   Write       [8]byte           //WriteTime
   FileSz      [4]byte           //FileSize
   IconIndex   [4]byte           //IconIndex
   ShowCmd     [4]byte           //ShowCommand

   //[2]byte HotKey values for shortcut shortcuts
   HotKeyLow   byte              //HotKeyLow
   HotKeyHigh  byte              //HotKeyHigh

   Reserved1   [2]byte           //Reserved1
   Reserved2   [4]byte           //Reserved2
   Reserved3   [4]byte           //Reserved3
}

That project should give you an idea to how to decode the shortcut target.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Does [os.Readlink(path)](https://golang.org/pkg/os/#Readlink) not work on Windows? – jrefior May 24 '17 at 21:34
  • 2
    @jrefior for symlink (`mklink` or maybe junction: `mklink /J`), as seen in https://github.com/golang/go/issues/15978. Not for "shortcut" (`lnk`) – VonC May 24 '17 at 21:35
  • @VonC can you write a little example on how to get that info? I'm very lost with this one :( – Emi May 24 '17 at 23:29
  • 1
    @CoppolaEmilio I will, tomorrow (a bit late here at the moment) – VonC May 24 '17 at 23:35
  • @VonC Sorry to pest you, but can you help me now? I want to accept the answer :) – Emi May 25 '17 at 16:23
  • @CoppolaEmilio I didn't get far: you can clone the repo and go build it: it will give you a `shortcut.exe` utility that you can use on your `.lnk` file: `shortcut -file c:\path\to\ashortcut.lnk`. But the destination path isn't directly detected. I !suspect it needs to be interpreted and reassembled, following the Microsoft spec. – VonC May 25 '17 at 16:46
  • 1
    @CoppolaEmilio In short, it helps you decoding the structure of a .lnk file, but a bit more work is required in order to retrieve the actual destination path. – VonC May 25 '17 at 16:47