.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# の方法がまだ見つかりません。それとも、これがこの種のことを行うための最良の方法ですか?