【发布时间】: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 来实现这一点。