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
반응형
'다양한 실전소스코드 > WINFORM(C#)' 카테고리의 다른 글
Tstory API로 블로그 글 쓰기 전 과정 C# (23년 8월) (0) | 2023.08.10 |
---|---|
C#에서 폴더 강제 삭제하기 (0) | 2023.01.03 |
[Solved] C# DataTable Sort, Get Special Column (0) | 2021.06.29 |
C# Debug.WriteLine 사용 (0) | 2021.06.29 |
[Solved] C# Datatable DefaultView Sort, Row FIlter (테이블 정렬 및 필터) (0) | 2021.06.29 |
댓글