如果路径/文件是快捷方式,我该如何以编程方式进行测试? [英] How can I test programmatically if a path/file is a shortcut?

查看:62
本文介绍了如果路径/文件是快捷方式,我该如何以编程方式进行测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试文件是否为快捷方式.我仍在尝试弄清楚如何设置内容,但我可能只有它的路径,我可能只有文件的实际内容(作为byte []),或者可能两者都有.

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.

一些复杂之处包括我可以将其保存在zip文件中(在这种情况下,该路径将是内部路径)

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

推荐答案

可以使用SHELL32.DLL中的COM对象来操作快捷方式.

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

在Visual Studio项目中,添加对COM库"Microsoft Shell控件和自动化"的引用,然后使用以下命令:

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
    }

这篇关于如果路径/文件是快捷方式,我该如何以编程方式进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆