如何从文件快捷方式获取路径名?获得例外

use*_*587 9 c# windows-shell

可能重复:
获取快捷方式文件夹的目标

例如,在C:\TEMP\我有一个名为test.dll快捷方式的快捷方式将导致文件名test.dll

我想从快捷方式只获取路径名到它自己的文件.所以,我在另一个递归函数中调用此函数,并在每次从我的硬盘中的另一个目录中放入此函数.

例如,第一个目录C:\TEMP就在C:\TEMP那里有快捷方式文件,我只想获取文件的路径.在C:\TEMP测试中,我现在有3个文件:

hpwins23.dat
hpwmdl23.dat
hpwmdl23.dat - Shortcut(C:\TEMP\hpwmdl23.dat)

所以,我想得到的是快捷方式的路径名,本例中是C:\ TEMP

我试着使用这个功能:

public string GetShortcutTargetFile(string shortcutFilename)
        {
            string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
            string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
            Shell shell = new Shell();
            Folder folder = shell.NameSpace(pathOnly);
            if (folder == null)
            {
            }
            else
            {
                FolderItem folderItem = folder.ParseName(filenameOnly);
                if (folderItem != null)
                {
                    Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
                    return link.Path;
                }
            }
            return string.Empty;
        }
Run Code Online (Sandbox Code Playgroud)

但是当我使用该函数并且它到达一个快捷方式时,我遇到异常错误:

Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink //The exception is: NotImplementedException: The method or operation is not implemented
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能解决它?

这是完整的异常错误消息:

System.NotImplementedException被捕获的
消息 =未实现方法或操作.
来源 = GatherLinks
堆栈跟踪:
Shell32.FolderItem.get_GetLink()
GatherLinks.Form1.GetShortcutTargetFile(String shortcutFilename)
D:\C-Sharp\GatherLinks\GatherLinks\GatherLinks\Form1.cs:line 904
GatherLinks.Form1.offlinecrawling

Pic*_*are 28

要获得快捷方式(.lnk文件扩展名)的目标,首先需要具有以下COM对象:Windows Script Host Object Model

然后,您可以使用WshShell(或WshShellClass)和IWshShortcut接口来获取快捷方式的目标

            string linkPathName = @"D:\Picrofo Autobot.lnk"; // Change this to the shortcut path

            if (System.IO.File.Exists(linkPathName))
            {
             // WshShellClass shell = new WshShellClass();
                WshShell shell = new WshShell(); //Create a new WshShell Interface
                IWshShortcut link = (IWshShortcut)shell.CreateShortcut(linkPathName); //Link the interface to our shortcut

                MessageBox.Show(link.TargetPath); //Show the target in a MessageBox using IWshShortcut
            } 
Run Code Online (Sandbox Code Playgroud)

谢谢,
我希望你觉得这很有帮助:)


您可以尝试以下步骤添加Windows Script Host Object Model到项目中

  • Solution Explorer下,右键单击项目名称,然后选择Add Reference
  • 从弹出窗口中选择选项卡COM
  • 在" 组件名称"下,选择" Windows脚本宿主对象模型"
  • 单击" 确定"

  • 我试图从以下位置读取lnk快捷方式:C:\ ProgramData \ Microsoft \ Windows \ Start Menu \ Programs \ StartUp \ shortcut.lnk,我从HRESULT:0x80020009(DISP_E_EXCEPTION)获取COMException :。我的操作系统:Win 8.1 x64 (2认同)