How can I test programmatically if a path/file is a shortcut?

一个人想着一个人 提交于 2019-11-30 04:48:28

问题


I need to test if a file is a shortcut. I'm still trying to figure out how stuff will be set up, but I might only have it's path, I might only have the actual contents of the file (as a byte[]) or I might have both.

A few complications include that I it could be in a zip file (in this cases the path will be an internal path)


回答1:


Shortcuts can be manipulated using the COM objects in SHELL32.DLL.

In your Visual Studio project, add a reference to the COM library "Microsoft Shell Controls And Automation" and then use the following:

/// <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
}

You can get the actual target of the link as follows:

    /// <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
    }



回答2:


You can simply check the extension and/or contents of this file. It contains a special GUID in the header.

Read this document.




回答3:


Check the extension? (.lnk)



来源:https://stackoverflow.com/questions/310595/how-can-i-test-programmatically-if-a-path-file-is-a-shortcut

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