< IniFile.cs >
namespace StudentApp
{
internal class iniFile
{
// 필드
public string filePath = "students.ini"; // 이것도 지정하면 좋을것같은데
// 메서드
public void writeFile(List<Student> students)
{
try
{
StreamWriter writer = new StreamWriter(filePath);
foreach (var student in students)
{
writer.WriteLine($"[{student.Name}]\nAge={student.Age}\nMajor={student.Major}\n");
}
writer.Close();
MessageBox.Show("학생 정보가 저장되었습니다.");
}
catch (Exception ex)
{
MessageBox.Show($"파일 저장 중 오류가 발생했습니다: {ex.Message}");
}
}
public void readFile(List<Student> students, ListBox listStudents)
{
try
{
// 파일 열기
StreamReader reader = new StreamReader(filePath);
students?.Clear();
listStudents?.Items.Clear();
parseIniFile(reader, students, listStudents); // 파싱 함수 호출!
reader.Close(); // 파일 닫기
MessageBox.Show("불러오기 완료");
}
catch (Exception ex)
{
MessageBox.Show($"파일 읽기 중 오류가 발생했습니다: {ex.Message}");
}
}
public void parseIniFile(StreamReader reader, List<Student> students, ListBox listStudents)
{
// 파싱값을 담을 변수들
string line;
string name = "";
int age = 0;
string major = "";
// ~반복문으로 한 줄씩 읽기~
while ((line = reader.ReadLine()) != null) // ReadLine이 EOF에 도달하면 null을 반환함
{
line = line.Trim(); // 공백 제거
if (string.IsNullOrWhiteSpace(line)) // 빈 줄이면 무시
{
continue;
}
// 대괄호 = 섹션 (파싱 시작)
if (line.StartsWith("[") && line.EndsWith("]")) // 1.이름
{
// 이름 변수가 비어있지 않으면 (비어있으면 조건문 통과)
if (!string.IsNullOrEmpty(name))
{
students.Add(new Student(name, age, major)); // 객체 생성!
listStudents.Items.Add(name);
}
// 새 학생 이름 초기화
name = line.Substring(1, (line.Length - 2)); // 여기서 이름을 담고 나가요 (나머지는 다음 조건문에서 담아요)
age = 0;
major = "";
// [이름]
// 이름에 대괄호 제거하고 저장 > 추출을 시작할 문자 위치, 끝나는 위치 (총 길이 -1은 대괄호)
// 이름이 3글자 이상일 수 있으니 길이로계산
}
// [나이]
else if (line.StartsWith("Age=")) // 2.나이
{
age = int.Parse(line.Substring(4)); // 4글자 이후부터 끝까지
}
// [전공]
else if (line.StartsWith("Major=")) // 3.전공
{
major = line.Substring(6); // 6글자 이후부터 끝까지
}
}
if (!string.IsNullOrEmpty(name)) // 이름이 비어있지 않다면
{
students.Add(new Student(name, age, major)); // 학생 리스트에 학생 추가 (일단 기본값으로 먼저 생성)
listStudents.Items.Add(name); // 리스트 박스에 이름 추가
}
}
}
}
// 파일 저장
private void btnSave_Click(object sender, EventArgs e)
{
iniFile iniWriter = new iniFile();
iniWriter.writeFile(students);
}
// 파일 읽기
private void btnOpen_Click(object sender, EventArgs e)
{
iniFile iniReader = new iniFile();
iniReader.readFile(students, listStudents);
}
btnSave함수와 btnOpen함수이다.
둘다 똑같이 iniFile 클래스로 각각 인스턴스를 생성해주었다.
이렇게되면 문제가 버튼을 클릭 할 때 마다 인스턴스가 생성된다.
하지만 굳이 이렇게 할 필요없이
하나의 인스턴스를 전역에 생성해서 이 함수에도 쓰고, 저 함수에도 쓰면 된다.
이렇게 여러 곳에 쓰일 상황이라면 필드에 변수를 생성하면 된다.
반대로 함수 내부에서만 쓰이고 말 변수라면 지역변수로 생성하면 된다.
'C#' 카테고리의 다른 글
| 필드(Field) vs 속성(Property) (0) | 2025.11.04 |
|---|---|
| namespace와 using구문 (0) | 2025.11.04 |
| static void Main(string[] args) 의 의미 (0) | 2025.11.04 |
| static이 아닌 필드, 메서드 또는 속성에 개체 참조가 필요합니다. (0) | 2025.11.04 |
| 학생 조회 프로그램 - origin 코드 (0) | 2025.11.04 |