지정 폴더 내의 파일 내용 검색
1. 검색할 디렉토리를 지정한다
2. 해당 디렉토리에 있는 모든 파일의 리스트를 가져온다
3. 읽을 수 없는 파일을 정규식으로 걸러낸다
4. 검색할 텍스트와 일치하는 파일 이름을 출력
Program.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace FileSearch
{
class Program
{
static void Main()
{
string archiveDirectory = @"D:\\";
string searchText = "M00009 삭제할 행을 선택하세요.";
var files = from retrievedFile in Directory.EnumerateFiles(archiveDirectory, "*", System.IO.SearchOption.AllDirectories).CatchExceptions() select retrievedFile;
var regex = new Regex("((?:.*?)(?:\\.(png|jpg|exe|zip|7z|mp4|dll|pdb|xlsx|pdf|ppt|docx|ico|iso|svn-base|meta|msi|psd)))");
foreach (var f in files)
{
//zip, png, jpg, exe 등 파일은 제외
if (regex.IsMatch(f))
{
continue;
}
else
{
try
{
var a = File.ReadLines(f, Encoding.UTF8).CatchExceptions().Any(x => x.Contains(searchText));
if (a == true)
{
Console.WriteLine("success : " + f);
}
}
catch (Exception)
{
continue;
}
}
}
}
}
}
CatchException 이라는 확장함수를 사용하는 이유는 Linq로 List를 돌리는 와중에 Exception이 나오면 프로그램이 멈추는것을 방지하게 위해서이다.
LinqExt.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace FileSearch
{
static class ExtLinq
{
public static IEnumerable<T> CatchExceptions<T>(this IEnumerable<T> src, Action<Exception> action = null)
{
using (var enumerator = src.GetEnumerator())
{
bool next = true;
while (next)
{
try
{
next = enumerator.MoveNext();
}
catch (Exception ex)
{
if (action != null)
{
action(ex);
}
continue;
}
if (next)
{
yield return enumerator.Current;
}
}
}
}
}
}
'C#' 카테고리의 다른 글
C# 파일 압축하기 (0) | 2020.03.07 |
---|---|
C# Xml의 노드의 값 일괄 변환 (0) | 2020.03.07 |
댓글