回到 .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# 方法。有没有,或者这仍然是做这类事情的最佳方式?