LoginSignup
9
8

More than 5 years have passed since last update.

【C#】ショートカットのリンク先取得

Posted at

00. はじめに

ファイルのドラッグ&ドロップを許可する場合、指定のファイルのみだけではなく、ファイルへのショートカットも受け付けるようにした方がUXが良いように思えます。
ここではショートカットのリンク先を取得する方法を記載します。
なお、ここでいうショートカットは".lnk"拡張子であり、".url"のインターネットショートカットではないです。
(".url"はただのテキストファイルですし...)

01. 参照の追加

参照マネージャーの"COM"から
"Windows Script Host Object Model"
にチェックを入れます。
pro01.png

02. コード

// ドロップ時のイベント
private void DragDrop(object sender, DragEventArgs e)
{
    // ドロップされたファイルを順に確認する
    foreach (string file in (string[])e.Data.GetData(DataFormats.FileDrop))
    {
        // ファイルの拡張子を取得
        string extension = Path.GetExtension(file);
        // ファイルへのショートカットは拡張子".lnk"
        if (".lnk" == extension)
        {
            IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
            // ショートカットオブジェクトの取得
            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(file);

            // ショートカットのリンク先の取得
            string targetPath = shortcut.TargetPath.ToString();
        }
    }
}

"Windows Script Host Object Model"の詳細は以下を参照
Windows Script Host のオブジェクト モデル | https://msdn.microsoft.com/ja-jp/library/cc392522.aspx

98. 参考

C#によるショートカットファイルのリンク先ファイルのパス名取得の試作 | https://blogs.yahoo.co.jp/tinatina_2013/64256895.html

99. 更新履歴

日付 内容
2018/04/16 投稿
9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8