chaoskcuf's lab

POST : 프로그래밍/TIP& Study

[C#] 텍스트 파일에서 원하는 줄만 가져오기

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 함수를 불러서 사용할 경우 주의하셔야 합니다.

2008/06/23 18:18 2008/06/23 18:18
top

tags

, ,

posted at

2008/06/23 18:18


◀ recent : [1] : ... [3] : [4] : [5] : [6] : [7] : [8] : [9] : [10] : [11] : ... [138] : previous ▶

CONTENTS

chaoskcuf's lab
BLOG main image
WPF, Silverlight, C#, MFC 프로그래밍 팁, 자작 프로그램 개발
RSS 2.0Tattertools 믹시
최근 글 최근 댓글 최근 트랙백
카테고리
사이트 링크