'텍스트파일검색'에 해당되는 글 1건

  1. 2008.11.18 [C#] 특정 내용이 있는 파일 검색하기
2008. 11. 18. 13:19

[C#] 특정 내용이 있는 파일 검색하기

반응형
요즘 C#을 간간히 사용해보는 중인데 정말 간단하게 구현이 되는게 많네요.
간단한 유틸은 C#으로 만드는게 상당히 유용한거 같습니다.

using System.IO;

bool bExist = false;
string sPath = @"C:\text.txt";

string sContents = File.ReadAllText(sPath, Encoding.Default);

int result = sContents.IndexOf("검색어");

if (result != -1)
    bExist = true;

그냥 File클래스의 ReadAllText하고 거기 내용 검색 하면 끝.
처음에는 StreamReader로 읽어서 ReadLine()으로 한줄한줄 읽어 와서 검색했었는데
ReadAllText를 이용 하니 365개의 파일 검색하는게 이전방식(StreamReader -> ReadLine -> Contains)으로 8초 정도 걸리던게 지금(File.ReadAllText -> IndexOf)은 600ms 정도 걸리네요.

추가.
StreamReader로도 좀 더 개선할 수 있더군요.
StreamReader sr = new StreamReader(fi.FullName, Encoding.Default);
string sContents = sr.ReadToEnd();
ReadLine은 한줄단위고 그냥 한꺼번에 읽어 올 수 있는 ReadToEnd함수가 있군요.