【问题标题】:Is there a way to follow a windows fileystem shortcuts programatically in C# without using COM?有没有办法在不使用 COM 的情况下在 C# 中以编程方式遵循 Windows 文件系统快捷方式?
【发布时间】:2009-03-11 21:07:42
【问题描述】:

回到 .NET 1.0 天,我写了一个方法来返回 MS Windows 上快捷方式的目标。它通过使用与 Windows 脚本宿主对象模型的互操作并通过 COM 接口暴力破解来做到这一点:

private FileInfo GetFileFromShortcut(FileInfo shortcut)
{
    FileInfo targetFile = null;

    try
    {
        IWshRuntimeLibrary.WshShell wShell = new IWshRuntimeLibrary.WshShellClass();
        IWshRuntimeLibrary.WshShortcut wShortcut = (IWshRuntimeLibrary.WshShortcut)wShell.CreateShortcut(shortcut.FullName);

        // if the file wasn't a shortcut then the TargetPath comes back empty
        string targetName = wShortcut.TargetPath;
        if (targetName.Length > 0)
        {
            targetFile = new FileInfo(targetName);
        }
    }
    catch (Exception)
    { // will return a null targetFile if anything goes wrong
    }

    return targetFile;
}

这仍然困扰着我,我想用更优雅的东西替换它,但前提是替换至少也能正常工作。我仍然找不到找到快捷方式目标的本机 C# 方法。有没有,或者这仍然是做这类事情的最佳方式?

【问题讨论】:

  • 好问题。没有想过如何在没有 COM 互操作的情况下使其正常工作
  • 不幸的是,我无法避免通过非托管代码使用 shell 来实现这一点。

标签: c# windows shortcuts


【解决方案1】:

看起来有人用 C# 编写了一个类来操作快捷方式文件,名为 ShellLink,但它也使用了 COM。

【讨论】:

  • 将 COM 活动隐藏在另一层后面并不是我真正想做的 - 我想将此代码发布到一个开源项目中并且不喜欢 COM bashing 部分。但如果没有别的办法......
  • 为什么不想使用 COM? Usign IShellLink 是做事的正确方法,因为这是 Windows 为快捷方式解析/修改提供的 API。您使用 Windows Scripting Host 的原始代码并不是最好的处理方式,但那是因为它使用了为脚本语言设计的包装器对象,而不是因为它使用了 COM 对象。 COM 在 Windows 上一直在幕后使用;这是不可避免的。
【解决方案2】:

你不能直接打开 .lnk 或 .url 文件并解析它吗?

这谈到了同样的事情并显示了文件的样子: http://www.programmingtalk.com/showthread.php?t=7335

【讨论】:

  • 我不确定解析一个没有发布定义的文件是我想要在我的生产代码中依赖的东西。有一个安全的解决方法是抨击 COM 接口,至少我知道这将永远有效。
【解决方案3】:

不久前我也对这个感兴趣。

这是已接受的response,带有指向 LNK 文件的(非正式)description of the format 的链接。显然,所有可用的方法通过一些 API。

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 2016-01-27
    • 2020-04-26
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多