C#
C# OpenFileDialog (파일 불러오기, 파일 열기)
sheepone
2021. 7. 12. 10:11
반응형
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp43
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var fileContent = string.Empty;
var filePath = string.Empty;
using (OpenFileDialog fd = new OpenFileDialog())
{
fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //바탕화면으로 기본폴더 설정
fd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; //필터 설정
fd.FilterIndex = 1; //1번 선택시 txt , 2번 선택시 *.*
if (fd.ShowDialog() == DialogResult.OK)
{
filePath = fd.FileName; //전체 경로와 파일명 //선택한 파일명은 fd.SafeFileName
}
}
//선택된 경로 파일 내용 읽기
var fileStream = new FileStream(filePath,FileMode.Open); //fd.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
fileContent = reader.ReadToEnd();
}
richTextBox1.Clear();
richTextBox1.AppendText(filePath);
richTextBox1.AppendText(fileContent);
}
}
}
실행화면 결과

반응형