C# ドラッグ&ドロップしたディレクトリ階層を表示
使用するもの
TextBox 1
TreeView 1
TextBoxはイベント「DragDrop」、「DragEnter」を使用。
※TextBoxのプロパティ「ArrowDrap」をtrueにすること。
※ドライブには対応してません。
試しにトイウォーズフォルダ表示 (怒られる?)
using System.Collections.Generic; using System.Windows.Forms; using System.IO; namespace TreeView { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_DragDrop(object sender, DragEventArgs e) { string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false); List<TreeNode> list = new List<TreeNode>(); foreach (var dir in s) { var tree = new TreeNode(dir); if (Directory.Exists(dir)) { var directory = new DirectoryInfo(dir); DirectoryHierarchy(tree, directory); } tree.Text = Path.GetFileName(dir); list.Add(tree); } treeView1.Nodes.Clear(); treeView1.Nodes.AddRange(list.ToArray()); } private void textBox1_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.All; else e.Effect = DragDropEffects.None; } private void DirectoryHierarchy(TreeNode parent, DirectoryInfo dir) { // ディレクトリ foreach (var dir2 in dir.GetDirectories()) { TreeNode child = new TreeNode(dir2.Name, 1, 2); parent.Nodes.Add(child); DirectoryHierarchy(child, dir2); } // ファイル foreach (var file in dir.GetFiles()) { // テキストファイルのみ追加 //if (file.Extension == ".txt"){} TreeNode child = new TreeNode(file.Name, 3, 3); parent.Nodes.Add(child); } } } }