1
2

More than 3 years have passed since last update.

C# - Windowsのリンクファイル(.lnk)からリンク先情報を取得する / Drag&Dropサンプル

Last updated at Posted at 2019-11-24

サンプルコード

フォームにlnkファイルをDrag&Dropすると、コンソールにlnkファイル自身のパスとリンク先パスを出力します。


using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Windows.Forms;

class ShortcutTest : Form
{
    public static string GetTargetPath(string fullPath)
    {
        dynamic shell = null;   // IWshRuntimeLibrary.WshShell
        dynamic lnk = null;     // IWshRuntimeLibrary.IWshShortcut
        try {
            var type = Type.GetTypeFromProgID("WScript.Shell");
            shell = Activator.CreateInstance(type);
            lnk = shell.CreateShortcut(fullPath);

            if (string.IsNullOrEmpty(lnk.TargetPath)) {
                return "lnk file does not exists.";
            }

            //lnk.Arguments,
            //lnk.Description,
            //lnk.FullName,
            //lnk.Hotkey,
            //lnk.IconLocation,
            //lnk.TargetPath,
            //lnk.WindowStyle,
            //lnk.WorkingDirectory

            return lnk.TargetPath;
        }
        finally {
            if (lnk != null) Marshal.ReleaseComObject(lnk);
            if (shell != null) Marshal.ReleaseComObject(shell);
        }
    }

    ShortcutTest()
    {
        this.AllowDrop = true;

        this.DragEnter += (sender,e) => {
            // e は DragEventArgs
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
                e.Effect = DragDropEffects.Copy;
            }
            else {
                e.Effect = DragDropEffects.None;
            }
        };
        this.DragDrop += (sender,e) => {
            var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            if (fileNames != null) {
                foreach(string s in fileNames){
                    if ( s.EndsWith(".lnk", true, null) ) {// Note: 第2引数はignoreCase
                        Console.WriteLine(s);
                        Console.WriteLine(" -> " + GetTargetPath(s));
                    }
                    else {
                        Console.WriteLine(s);
                    }
                }
            }
        };
    }

    [STAThread]
    static void Main(string[] args)
    {
        Application.Run(new ShortcutTest());
    }
}

実行結果


C:\SvnLocal\trunk\LnkFile\Command Prompt.lnk
 -> C:\Windows\system32\cmd.exe

参考サイト

  1. [C#] ショートカットファイル(.lnk)の内容を取得する1
  2. Drag&Dropされたファイルのファイル名を取得する - dobon.net

  1. 1のコードは、C#バージョン7で導入されたTupleを使用しているので、そのままだと、デフォルトで入っているcsc.exeではコンパイルできないかもしれません。 

1
2
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
1
2