2008-11-22 77 views
6

我需要测试一个文件是否是一个快捷方式。我仍然试图找出如何设置东西,但我可能只有它的路径,我可能只有文件的实际内容(作为一个字节[]),或者我可能都有。如何以编程方式测试路径/文件是否是快捷方式?

一些并发症包括我它可能是一个zip文件(在这种情况下,路径将是一个内部路径)

回答

14

使用SHELL32.DLL中的COM对象可以处理快捷方式。

在Visual Studio项目中,添加对COM库“微软壳牌控制及自动化”的引用,然后使用以下命令:

/// <summary> 
/// Returns whether the given path/file is a link 
/// </summary> 
/// <param name="shortcutFilename"></param> 
/// <returns></returns> 
public static bool IsLink(string shortcutFilename) 
{ 
    string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename); 
    string filenameOnly = System.IO.Path.GetFileName(shortcutFilename); 

    Shell32.Shell shell = new Shell32.ShellClass(); 
    Shell32.Folder folder = shell.NameSpace(pathOnly); 
    Shell32.FolderItem folderItem = folder.ParseName(filenameOnly); 
    if (folderItem != null) 
    { 
     return folderItem.IsLink; 
    } 
    return false; // not found 
} 

你可以得到链路的实际目标如下:

/// <summary> 
    /// If path/file is a link returns the full pathname of the target, 
    /// Else return the original pathnameo "" if the file/path can't be found 
    /// </summary> 
    /// <param name="shortcutFilename"></param> 
    /// <returns></returns> 
    public static string GetShortcutTarget(string shortcutFilename) 
    { 
     string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename); 
     string filenameOnly = System.IO.Path.GetFileName(shortcutFilename); 

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

除了快捷方式是在一个zip文件(我假设,我没有测试过这种情况)或我拥有的只是它作为一个字节缓冲区的情况除外。 – BCS 2008-11-22 00:49:44

3

你可以简单地检查该文件的扩展名和/或内容。它在标题中包含一个特殊的GUID。

阅读this document

+3

链接中断 – Letseatlunch 2013-06-13 19:04:48

-1

检查扩展名? (.lnk)

相关问题