Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8901

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

$
0
0

サンプルコード

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

usingSystem;usingSystem.Runtime.InteropServices;usingSystem.Drawing;usingSystem.Windows.Forms;classShortcutTest:Form{publicstaticstringGetTargetPath(stringfullPath){dynamicshell=null;// IWshRuntimeLibrary.WshShelldynamiclnk=null;// IWshRuntimeLibrary.IWshShortcuttry{vartype=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.WorkingDirectoryreturnlnk.TargetPath;}finally{if(lnk!=null)Marshal.ReleaseComObject(lnk);if(shell!=null)Marshal.ReleaseComObject(shell);}}ShortcutTest(){this.AllowDrop=true;this.DragEnter+=(sender,e)=>{// e は DragEventArgsif(e.Data.GetDataPresent(DataFormats.FileDrop)){e.Effect=DragDropEffects.Copy;}else{e.Effect=DragDropEffects.None;}};this.DragDrop+=(sender,e)=>{varfileNames=(string[])e.Data.GetData(DataFormats.FileDrop,false);if(fileNames!=null){foreach(stringsinfileNames){if(s.EndsWith(".lnk",true,null)){// Note: 第2引数はignoreCaseConsole.WriteLine(s);Console.WriteLine(" -> "+GetTargetPath(s));}else{Console.WriteLine(s);}}}};}[STAThread]staticvoidMain(string[]args){Application.Run(newShortcutTest());}}

実行結果

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ではコンパイルできないかもしれません。 


Viewing all articles
Browse latest Browse all 8901

Trending Articles