2012-10-26 46 views
7

可能重複:
Get target of shortcut folder如何從文件快捷方式獲取路徑名?獲取例外

例如,在C:\TEMP\我有一個名爲test.dll快捷鍵的快捷方式將導致文件名test.dll

我想從只有路徑名的快捷方式到它自己的文件。 所以,我在另一個遞歸函數中調用了這個函數,並且每次從我的硬盤上放入另一個目錄時,都要在這個函數中加入這個函數。

例如,第一個目錄是C:\TEMP然後在C:\TEMP有一個快捷方式文件,我只想獲取文件的路徑。在C:\TEMP的測試我現在有3個文件:

hpwins23.dat
hpwmdl23.dat
hpwmdl23.dat - ShortcutC:\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; 
     } 

,但是當我使用的功能和它前往一個快捷方式我就行了越來越異常錯誤:

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

我務必做好解決呢?

這是完整異常錯誤消息:

System.NotImplementedException被抓住
消息 =的方法或操作未實現。
= GatherLinks
堆棧跟蹤
Shell32.FolderItem.get_GetLink()
GatherLinks.Form1.GetShortcutTargetFile(String shortcutFilename)
D:\C-Sharp\GatherLinks\GatherLinks\GatherLinks\Form1.csline904
GatherLinks.Form1.offlinecrawling

+0

此用戶最有可能要求解決的符號鏈接(沒有快捷方式在.LNK),在這種情況下,該代碼將失敗。你需要在PInvoke中使用'GetFinalPathNameByHandle()'。示例代碼可以在[此處輸入](http://chrisbensen.blogspot.com/2010/06/getfinalpathnamebyhandle.html)中找到。 – ykay

回答

18

爲了得到一個快捷方式(.lnk文件擴展名)的目標you'l升首先需要具備以下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 
      } 

謝謝,
我希望你覺得這有幫助:)


你可以試試下面的步驟添加Windows Script Host Object Model到項目

  • 解決方案資源管理器,右鍵單擊您的項目名稱並選擇添加引用
  • 從選擇標籤COM彈出窗口
  • 組件名稱,請選擇Windows腳本宿主對象模型
  • 點擊OK
+0

我試圖從以下位置讀取lnk-shortcut:C:\ ProgramData \ Microsoft \ Windows \ Start Menu \ Programs \ StartUp \ shortcut.lnk,並且我得到COMException:從HRESULT:0x80020009(DISP_E_EXCEPTION)。我的操作系統:Win 8.1 x64 –