C# TXT파일 접근 - StreamReader, StreamWriter
[Notice]
-DoriDori님의 C# 강의를 바탕으로 한다.
-강의의 모든 내용을 정리한다는 것 보다는 필요한 부분만 발췌해서 정리할 것이다.
-소스코드도 일부만 발췌한다.
0.UI 정보
- Txt 파일 읽어오기 버튼 - Name: btnLoad
- Txt 파일 저장하기 버튼 - Name: btnSave
- Txt 파일 내용 보여주는 박스 - Name : tboxConfigData
1. StreamReader, StreamWriter
*텍스트 파일을 읽거나 쓰기 위해 사용한다
*불러 올 때는 StreamReader, 저장 할 때는 StreamWrite Class 사용한다
*System.IO.File.Class 에서 비슷한 기능의 함수를 제공한다.
- File.ReadAllText("경로"); // 반환 : String 형태
- File.ReadAllLines("경로"); //반환 : String [](배열) 형태
- File.WriteAllText("경로", "읽어 올 Text File"); // 반환 : Text File로 저장
- File.WriteAllLines("경로", "배열형태의 String Data"); // 반환 : Text File로 저장
*사용방식
-Program File의 Log를 기록 하거나 기록된 Log를 읽어 올 때 사용한다
-프로그램 동작에 필요한 자료를 저장해 두거나 불러와서 사용한다.
(데이터를 저장하는 방식은 XML 형태나 DB형태로 발전 가능하다.)
-Log를 많이 남길 수록 프로그램 분석에 유용
2. SaveFileDialog : 파일 세이브 할때 뜨는 창이 뜬다.(도구 상자에 있음)
3. OpenFileDialog : 파일을 여는 윈도우가 열린다.(도구 상자에 있음)
4.소스코드 분석
1)코드 블럭
private void btnSave_Click(object sender, EventArgs e)//파일 저장하기 버튼
{
//SFDialog는 SaveFileDialog의 객체
string strFilePath = string.Empty;
SFDialog.InitialDirectory = Application.StartupPath; // 프로그램이 시작하는 폴더가 들어간다. (프로그램 실행 파일 위치)
SFDialog.FileName = "*txt"; // 파일이름에 들어가는 확장자
SFDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
// txt files(*.txt) 누르면 *.txt 만 폴더에서 필터링 되고
//All files(*.*) 누르면 *.* 만 폴더에서 필터링한다.
//*는 모든 문자열이다. 즉, (*.txt)는 txt인 모든 파일을 말한다.
if(SFDialog.ShowDialog() == DialogResult.OK)// Show Dialog는 팝업 뜨게 하는것. DialogResult.OK는 저장하는 버튼
{
strFilePath = SFDialog.FileName; // 저장할 파일 이름과 경로 까지 전부 포함
StreamWriter swSFDialog = new StreamWriter(strFilePath); //System.IO에 있는 것 쓴다.
//StreamWriter로 객체를 만들면 생성자에 저장할 파일 이름과 경로까지 전부 줘야한다.
swSFDialog.WriteLine(tboxConfigData.Text); // 저장한 파일을 tboxConfigData에 쓴다
swSFDialog.Close(); // 다 쓰고 닫는다
}
}
private void btnLoad_Click(object sender, EventArgs e)// 파일 불러오기 버튼
{
string strFilePath = string.Empty;
SFDialog.InitialDirectory = Application.StartupPath; // 프로그램이 시작하는 폴더가 들어간다. (프로그램 실행 파일 위치)
SFDialog.FileName = "*txt";// 파일이름에 들어가는 확장자
SFDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
StringBuilder sb = new StringBuilder();
if (OFDialog.ShowDialog() == DialogResult.OK) {
strFilePath = OFDialog.FileName;
StreamReader srOFDialog = new StreamReader(strFilePath, Encoding.UTF8, true); //문자 인코딩 형식 지정
while (srOFDialog.EndOfStream == false)// 마지막 줄이 아니면 계속 돈다.
{
sb.Append(srOFDialog.ReadLine()); //한 줄 씩 읽어온다. StringBuilder에 넣어서 문자열 편집의 편리성을 확보한다.
sb.Append("\r\n");// 한 줄 읽고 띄어쓰기
}
// 모든 줄을 sb에 넣고 나서
tboxConfigData.Text = sb.ToString(); //tboxConfigData에 넣는다.
}
}
2)캡쳐본
[출처]
표지
<a href="https://www.freepik.com/free-vector/evening-cloudy-sky-purple-background-with-group-cumulus-cirrus-clouds-flat-cartoon-illustration_16607919.htm#query=lofi%20background&position=24&from_view=keyword&track=ais">Image by macrovector</a> on Freepik
DoriDori님의 강의
https://www.youtube.com/watch?v=20hiaI2S6xQ&list=PLoFFz2j8yxxxH_3ustbHATXtMsHZ-Saei&index=21