C#

C# 파일 내용 검색

위ㄱㅎ 2020. 3. 7. 17:50

지정 폴더 내의 파일 내용 검색

 

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;
                    }
                }
            }
        }
    }
}