Better Search for a string in all files using C#
.net, c#, file-io
Solution
Instead of File.ReadAllText() better use
File.ReadLines(@"C:\file.txt");
It returns `IEnumerable` (yielded) so you will not have to read the whole file if your string is found before the last line of the text file is reached
Problem
After referring many blogs and articles, I have reached at the following code for searching for a string in all files inside a folder. It is working fine in my tests. QUESTIONS - Is there a faster approach for this (using C#)? - Is there any scenario that will fail with this code? Note: I tested with very small files. Also very few number of files. CODE ``` static void Main() { string sourceFolder = @"C:\Test"; string searchWord = ".class1"; List<string> allFiles = new List<string>(); AddFileNamesToList(sourceFolder, allFiles); foreach (string fileName in allFiles) { string contents = File.ReadAllText(fileName); if (contents.Contains(searchWord)) { Console.WriteLine(fileName); } } Console.WriteLine(" "); System.Console.ReadKey(); } public static void AddFileNamesToList(string sourceDir, List<string> allFiles) { string[] fileEntries = Directory.GetFiles(sourceDir); foreach (string fileName in fileEntries) { allFiles.Add(fileName); } //Recursion string[] subdirectoryEntries = Directory.GetDirectories(sourceDir); foreach (string item in subdirectoryEntries) { // Avoid "reparse points" if ((File.GetAttributes(item) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint) { AddFileNamesToList(item, allFiles); } } } ``` REFERENCE - Using StreamReader to check if a file contains a string - Splitting a String with two criteria - C# detect folder junctions in a path - Detect Symbolic Links, Junction Points, Mount Points and Hard Links - FolderBrowserDialog SelectedPath with reparse points - C# - High Quality Byte Array Conversion of Images
Related problems
- Is String.Contains() faster than String.IndexOf()?
- Using StreamReader to check if a file contains a string
- How do I create/edit a Manifest file?
- Detect Symbolic Links, Junction Points, Mount Points and Hard Links
- Boyer-Moore Practical in C#?
- C# detect folder junctions in a path
- FolderBrowserDialog SelectedPath with reparse points
- Splitting a String with two criteria