본문 바로가기
C++ 200제/코딩 IT 정보

C# 파일과 폴더, 드래그 앤 드롭 예제 (마우스 Drag Listview)

by vicddory 2017. 5. 7.

C# 파일과 폴더 정보, 드래그 앤 드롭 예제 (마우스 Drag Listview)


전체 프로젝트는 바로 아래에 있는 zip 파일을 참조하시면 됩니다.


여기에 파일을 올려보세요 아래에 마우스로 파일을 올려놓으면 파일 정보가 나오고,

여기에 폴더를 올려보세요 아래에 마우스로 폴더를 올려놓으면 폴더의 정보가 나옵니다.


C# 드래그 앤 드롭 프로젝트 - Csharp_DragAndDrop.zip [클릭]


우선, using System.ComponentModel;을 추가하여 DataFormats 클래스를 사용할 수 있도록 설정합니다.


- txtFileDrop_DragDrop 함수 : 파일 정보 추출 후 텍스트로 표시

- lDirDrop_DragDrop 함수 : 폴더 정보 추출 후 파일 내역 텍스트로 표시


C Sharp - DragDrop Example[C# 파일과 폴더 정보, 드래그 앤 드롭 예제 (마우스 Drag Listview)]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
 
namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            txtFileDrop.AllowDrop = true;
            lDirDrop.AllowDrop = true;
        }
 
        private void txtFileDrop_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy; //마우스 important to get the process to work
        }
 
        private void txtFileDrop_DragDrop(object sender, DragEventArgs e)
        {
            string[] fileNames = (string[])e.Data.GetData(DataFormats.FileDrop);
            txtFileDrop.Text = fileNames[0]; //Dragging only one file
        }
 
        private void lDirDrop_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
        }
 
        private void lDirDrop_DragDrop(object sender, DragEventArgs e)
        {
            string[] directoryName = (string[])e.Data.GetData(DataFormats.FileDrop);
 
            //Get all the folders inside that folder, 드래그 앤 드롭 폴더
            string[] dirs = Directory.GetDirectories(directoryName[0]);
 
            //Get all the files inside that folder, 드래그 앤 드롭 파일
            string[] files = Directory.GetFiles(directoryName[0]);
 
            lDirDrop.Items.Clear();
 
            foreach (string dir in dirs)
            {
                lDirDrop.Items.Add(dir);
            }
 
            foreach (string file in files)
            {
                lDirDrop.Items.Add(file);
            }
        }
    }
}
cs


DataFormats의 FileDrop을 이용해 단독 파일과 폴더의 파일 리스트 생성이 가능합니다.


폴더 내부의 파일들은 FileDrop를 이용해 순차적으로 파일들을 읽어들여, 리스트 박스 내부의 아이템으로 추가하는 형태로 이루어지는데 매우 간단합니다.


소스를 분석하실 때 Directory 클래스랑 DataFormats 클래스를 중심으로 파악하세요.


C# 파일과 폴더, 드래그 앤 드롭 예제 (마우스 Drag Listview)

댓글