How to get the target of a Windows shortcut file

S

Steve M

Below is some code adapted from something I think was written by Mark
Hammond. Originally I needed to create a Windows shortcut (link), and
this code does the trick, requiring only the target filename and the
desired shortcut name.
Now, I find I need to open a shortcut and extract the target filename,
and I don't have a clue how that is achieved. To be clear, I mostly
don't understand the gory (Windows API) details of this code. So, can
anyone show how to open an existing shortcut file (given its name) and
discover the name of the file to which it is a shortcut?


import os
from win32com.shell import shell
import pythoncom

# Get the shell interface.
sh = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, \
pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)

# Get an IPersist interface
persist = sh.QueryInterface(pythoncom.IID_IPersistFile)

target_of_link = os.path.abspath('target.doc')
link_name = 'shortcut_to_target.doc.lnk'

sh.SetPath(target_of_link)
persist.Save(link_name, 1)
 
R

Roger Upole

persist.Load('someshortcut.lnk')
print sh.GetPath(shell.SLGP_RAWPATH)[0]

hth
Roger
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top