2014-01-26 66 views
0

我正在尝试创建一个小程序,它将C#(控制台应用程序)中的快捷方式的目标文件名提取给用户。 我的代码没有错误,但它没有给我正确的结果。找不到快捷方式的目标

这是我的代码:就像我说的,代码检索我是错的输出(空字符串),即使该文件是存在

private static string GetTargetPath(string ShortcutPath) 
{ 
    string pathOnly = System.IO.Path.GetDirectoryName(ShortcutPath); 
    string filenameOnly = System.IO.Path.GetFileName(ShortcutPath); 

    Shell32.Shell shell = new Shell32.ShellClass(); 
    Shell32.Folder folder = shell.NameSpace(pathOnly); 
    Shell32.FolderItem folderItem = folder.ParseName(filenameOnly); 
    if (folderItem != null) 
    { 
     Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink; 
     return link.Path; 
    } 
    return ""; // not found 
} 

:(http://snipplr.com/view/47974了来自)。 例如,我厌倦了获取路径中某个快捷方式的目标文件:C:\ Users \ Admin123 \ AppData \ Roaming \ Microsoft \ Office \ Recent

这个问题的原因是什么?我该如何解决它?

编辑

我再次尝试相同的代码和现在的作品!谢谢大家 ! :)

+0

我相信你需要使用COM Interop Services来成功地使用Shell32.dll组件。我从来没有真正有过使用它的理由,所以我不想指出你错误的方向。以下是关于COM Interops的MSDN文章:http://msdn.microsoft.com/en-us/library/aa645712(v=vs.71).aspx – JNYRanger

+0

你只是想知道文件是否存在? – wruckie

回答

1

嗯,我看你的代码没有问题。经过测试,效果很好。

我创建了两个链接:boot.lnkprestigio_notes.lnk,两者都导致正确的文件。它们的输出分别是:

D:\Boot1.asmD:\Dokumenty\Android\Prestigio\doc\prestigio_notes.txt

这是我使用的代码(抱歉的复制粘贴功能再一次,但我希望它是一个完整的,明确的阶级):

class Program { 
    static void Main(string[] args) { 
     Console.WriteLine(GetTargetPath(@"D:\boot.lnk")); 
     Console.WriteLine(GetTargetPath(@"D:\prestigio_notes.lnk")); 
     Console.ReadLine(); 
    } 

    private static string GetTargetPath(string ShortcutPath) { 
     string pathOnly = System.IO.Path.GetDirectoryName(ShortcutPath); 
     string filenameOnly = System.IO.Path.GetFileName(ShortcutPath); 

     Shell32.Shell shell = new Shell32.Shell(); 
     Shell32.Folder folder = shell.NameSpace(pathOnly); 
     Shell32.FolderItem folderItem = folder.ParseName(filenameOnly); 
     if (folderItem != null) { 
      Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink; 
      return link.Path; 
     } 
     return ""; // not found 
    } 
} 

检查你是从引用正确的COM对象可用的参考列表。如果失败,请检查您是否有权从指定位置进行阅读。

+0

你是对的,现在我的代码神奇地工作,..谢谢你无论如何! – Aviv