C#에서 두 개의 텍스트 파일을 교차해서 읽어와 처리해야 하는 경우가 있을 때가 있죠.
예를 들어, 두 파일의 내용을 순차적으로 처리하면서 각 줄을 교차로 가져와 결과로 활용하고 싶을 때가 있습니다. 이럴 때 유용한 방법을 소개하겠습니다.
예시 코드
private void CrossAandB()
{
try
{
string result = string.Empty;
string lineA = string.Empty;
string lineB = string.Empty;
string pathA = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\A.txt";
string pathB = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\B.txt";
if (!File.Exists(pathA))
{
MessageBox.Show($"File A({pathA}) is not exists");
return;
}
if (!File.Exists(pathB))
{
MessageBox.Show($"File B({pathB}) is not exists");
return;
}
int lineCountA = File.ReadAllLines(pathA).Length;
int lineCountB = File.ReadAllLines(pathB).Length;
if (lineCountA != lineCountB)
{
MessageBox.Show($"lineCountA({lineCountA}) != lineCountB({lineCountB})");
return;
}
StringBuilder s = new StringBuilder();
using (StreamReader srA = new StreamReader(pathA))
{
using (StreamReader srB = new StreamReader(pathB))
{
while ((lineA = srA.ReadLine()) != null && (lineB = srB.ReadLine()) != null)
{
if (lineA == string.Empty)
continue;
s.AppendLine(lineA);
s.AppendLine(lineB);
}
}
}
result = s.ToString();
if (result.EndsWith(Environment.NewLine))
result = result.TrimEnd(Environment.NewLine.ToCharArray());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
코드 설명
먼저, 코드의 핵심은 두 개의 파일 A.txt와 B.txt가 같은 라인 수를 가지고 있는지 확인한 후, 각 줄을 순차적으로 읽어와 하나의 결과 문자열로 만드는 것입니다. 이 코드에서는 두 파일을 교차해서 읽은 후, 하나의 결과로 출력하는 흐름을 처리하고 있어요.
코드 동작 과정
- 파일 존재 여부 확인: 먼저
File.Exists()메서드를 사용해 A 파일과 B 파일이 존재하는지 확인합니다. 만약 파일이 없다면 메시지를 표시하고 작업을 종료해요. - 라인 수 비교: 두 파일이 같은 라인 수를 가지고 있는지를 확인합니다. 이때
File.ReadAllLines()메서드를 사용하여 각 파일의 총 라인 수를 가져옵니다. 만약 두 파일의 라인 수가 다르다면, 이를 알리는 메시지를 출력하고 함수가 종료해요. - 파일 교차 읽기:
StreamReader를 사용해 파일을 한 줄씩 읽어옵니다. 각 줄은lineA와lineB변수에 저장되며, 두 파일의 내용을 번갈아 가며StringBuilder객체에 추가해줍니다. 이 과정에서 빈 줄이 있는 경우는 건너뛰도록 설정했습니다. - 결과 처리: 모든 내용을 읽어온 후, 마지막에 줄바꿈 문자가 남아 있다면 이를 제거해 깔끔한 결과를 반환하도록 처리합니다.
