http://chaoskcuf.com/137#comment2972 에 대한 답변입니다.
첨부한 test.txt와 같이 line 단위로 이루어져 있는 파일이 있다고 가정을 하고,
이 파일에서 원하는 부분(예를 들어 100번째 열부터 10줄 단위로 )을 가져오고 싶을 때의 효과적인 방법입니다.
개념은 간단합니다.
StreamReader 객체로 ReadLine을 하면 Line을 읽고 난 다음의 위치를 StreamReader 객체가 기억하고 있기 때문에,
매번 파일을 열어서 해당 파일을 내용을 확인하고 파일을 닫고 하는 과정이 반복되게 코드를 작성하지 마시고,
StreamReader 객체를 한번만 선언하고 계속 그 객체를 이용하시기 바랍니다.
class Program
{
static StreamReader _sr = null;
static int _currentLine = 0;static void Main(string[] args)
{
try
{
_sr = new StreamReader("test.txt");
}
catch (Exception ex)
{
_sr = null;
Console.WriteLine(ex.Message);
}bool isSeekable = SeekLine(30); // 처음 몇 줄(예를 들어 30째 줄)을 건너뛰고 싶을 때
string[] a = GetNextLines(10); // 30번째 이후 10개 줄의 내용
string[] b = GetNextLines(10); // 40번째 이후 10개 줄의 내용
string[] c = GetNextLines(20); // 50번째 이후 20개 줄의 내용
}static bool SeekLine(int line)
{
if (_sr == null)
return false;for (int i = 0; i < line; i++)
{
if (string.IsNullOrEmpty(_sr.ReadLine()))
{
return false;
}
else
{
_currentLine++;
}
}return true;
}static string[] GetNextLines(int lines)
{
if (_sr == null)
return null;List<string> list = new List<string>();
string lineBuffer = string.Empty;
for (int i = 0; i < lines; i++)
{
lineBuffer = _sr.ReadLine();
if (string.IsNullOrEmpty(lineBuffer))
break;
list.Add(lineBuffer);
_currentLine++;
}
return list.ToArray();
}}
프로그램을 이전에 처리한 후 부터 다시 처리하고 싶을 경우 _currentLine 변수를 적절한 곳(레지스트리나 config 파일)에
저장해서 프로그램이 로드되는 시점에 SeekLine 함수를 불러주시면 될 것 같습니다.
그러나 여러 쓰레드에서 GetNextLines 함수를 불러서 사용할 경우 주의하셔야 합니다.

Program.cs
test.zip




