바라기의 모든 세상

C# 폴더 안까지 파일들 리스트로 만들기 본문

난 개발자다/C#

C# 폴더 안까지 파일들 리스트로 만들기

가까운행복 2022. 10. 7. 21:23
반응형

폴더 안 파일 리스트 만들기

폴더에 있는 파일 리스트 만드는 프로그램

하위 폴더도 까지도 리스트 만들어 줌

프로그램 작동 영상

https://youtu.be/-7poJ17JT6A

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.DirectoryServices;

namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

    //버튼 클릭
    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "진행 중";

        DirectorySearch(textBox1.Text);
        System.IO.File.WriteAllText(savepath, textvalue);
        label1.Text = "완료";
    }

    //변수 전역 설정
    String savepath = "D:\\test.txt";
    string textvalue = "";

    //메인 로직
    public void DirectorySearch(string dir)
    {
        if (dir == "" )
        {
            label1.Text = "경로를 입력하여 주세요";
            return;
        }
        DirectoryInfo di = new DirectoryInfo(dir);


        try
        {
            // 현재 폴더 파일 리스트
            foreach (FileInfo file in di.GetFiles())
            {   
                //Console.WriteLine(file.FullName);

                //파일 리스트 목록에 담기
                textvalue = textvalue + "\n" + file.FullName.ToString();
                //Console.WriteLine(file.Name);
            }


            //하위 폴더 검색후 되돌리기
            foreach (string d in Directory.GetDirectories(dir))
            {
                //textvalue = textvalue + "\n" + Path.GetFileNameWithoutExtension(d);
                //Console.WriteLine(Path.GetFileName(d));
                DirectorySearch(d);
            }

        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
        }


    }

    //종료 버튼
    private void button2_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    //폴더 선택
    private void textBox1_Click(object sender, EventArgs e)
    {
        //openFileDialog1.ShowDialog();

        //파일 선택
        //if (openFileDialog1.ShowDialog() == DialogResult.OK)
        //{

        //    try
        //    {
        //        var sr = new StreamReader(openFileDialog1.FileName);
        //        textBox1.Text = (sr.ReadToEnd());
        //    }
        //    catch (System.Exception ex)
        //    {
        //        MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
        //        $"Details:\n\n{ex.StackTrace}");
        //    }
        //}

        //폴더 선택
        FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

        if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
        {
            //MessageBox.Show(folderBrowserDialog.SelectedPath);
            textBox1.Text = (folderBrowserDialog.SelectedPath);
        }
    }
}

}

반응형
Comments