VB.NET / C# code to access target path of link (lnk) files produces some wrong paths

此生再无相见时 提交于 2019-12-10 22:35:06

问题


I found this code:

    Public Shared Function GetLnkTarget(ByVal lnkPath As String) As String
    Dim shl = New Shell32.Shell()
    ' Move this to class scope
    lnkPath = System.IO.Path.GetFullPath(lnkPath)
    Dim dir = shl.[NameSpace](System.IO.Path.GetDirectoryName(lnkPath))
    Dim itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath))
    Dim lnk = DirectCast(itm.GetLink, Shell32.ShellLinkObject)
    Return lnk.Target.Path
    End Function

It works for some .lnk files, but for example if I add my Skype.exe desktop link it produces:

C:\Windows\Installer\{...}\SkypeIcon.exe

Is there a fix for this?


回答1:


Try this:

Function GetTargetPath(ByVal FileName As String)

    Dim Obj As Object
    Obj = CreateObject("WScript.Shell")

    Dim Shortcut As Object
    Shortcut = Obj.CreateShortcut(FileName)
    GetTargetPath = Shortcut.TargetPath


End Function

    Private Sub Teste_Load(sender As Object, e As EventArgs) Handles MyBase.Load 

MsgBox(GetTargetPath("C:\ProgramData\Microsoft\Windows\Start Menu\BitTorrent.lnk"))

'here you chose the location of .lnk file

End Sub



回答2:


CreateShortcut() doesn't work as expected with certain shortcuts that have a greyed out target in the properties, like Adobe Reader and Microsoft Word. The targetpath ends up being something under c:\windows\installer (icon?).



来源:https://stackoverflow.com/questions/9454836/vb-net-c-sharp-code-to-access-target-path-of-link-lnk-files-produces-some-wr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!