본문 바로가기
다양한 실전소스코드/WINFORM(C#)

c# listbox에 txt목록 생성 + 클릭시 text 내용 표시

by aibattle 2023. 8. 9.
728x90
반응형

c# 특정 폴더 txt파일 listbox에 파일명 띄우고 , 목록 클릭하면 txt파일이 textbox1에 표시하는

내용입니다.

 

using System;
using System.IO;
using System.Windows.Forms;

namespace FileBrowser
{
    public partial class Form1 : Form
    {
        private string folderPath = "C:\\YourFolderPath"; // 여기에 폴더 경로를 지정하세요

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 폴더 내의 모든 텍스트 파일을 가져옵니다.
            string[] files = Directory.GetFiles(folderPath, "*.txt");

            // 파일명만 listBoxFiles에 추가합니다.
            foreach (string file in files)
            {
                listBoxFiles.Items.Add(Path.GetFileName(file));
            }
        }

        private void listBoxFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 선택한 파일의 내용을 읽어옵니다.
            string selectedFile = Path.Combine(folderPath, listBoxFiles.SelectedItem.ToString());
            string content = File.ReadAllText(selectedFile);

            // 내용을 textBox1에 표시합니다.
            textBox1.Text = content;
        }
    }
}

 

만약 하위폴더까지 모두 가져오려면

아래와 같이 수정해서 볼수 있습니다

 

using System;
using System.IO;
using System.Windows.Forms;

namespace FileBrowser
{
    public partial class Form1 : Form
    {
        private string folderPath = "C:\\YourFolderPath"; // 여기에 폴더 경로를 지정하세요

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 폴더와 하위 폴더 내의 모든 텍스트 파일을 가져옵니다.
            string[] files = Directory.GetFiles(folderPath, "*.txt", SearchOption.AllDirectories);

            // 파일명과 파일 경로를 listBoxFiles에 추가합니다.
            foreach (string file in files)
            {
                listBoxFiles.Items.Add(new FileItem { FileName = Path.GetFileName(file), FilePath = file });
            }

            listBoxFiles.DisplayMember = "FileName";
        }

        private void listBoxFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 선택한 파일의 내용을 읽어옵니다.
            FileItem selectedFileItem = (FileItem)listBoxFiles.SelectedItem;
            string content = File.ReadAllText(selectedFileItem.FilePath);

            // 내용을 textBox1에 표시합니다.
            textBox1.Text = content;
        }

        public class FileItem
        {
            public string FileName { get; set; }
            public string FilePath { get; set; }
        }
    }
}

즐거운 코딩하세요~

728x90
반응형

댓글