March 4, 2021

Search File Contents with LinqPad

Searching the contents of some file or files in LinqPad (a line at a time) in C# or even just finding a file:
Directory.EnumerateFiles(
  @"C:\Path\To\Search\Directory\", // Target of search
  "*.txt", // Specify file or files to search
  SearchOption.AllDirectories).  
  // SearchOption.AllDirectories - recusively search subdirectories
  // SearchOption.TopDirectoryOnly - search specified directory only
  // Next line records a line of text, the line number, and the file
  SelectMany(file => File.ReadAllLines(file).Select((text,n) => new {text,lineNumber=n+1,file})).
  // Here we search the text
  // Use Regex for the search OR use string methods Contains(), StartsWith, EndsWith ...
  Where(line => Regex.IsMatch(line.text, @"Searching for this text", RegexOptions.IgnoreCase)
                                            && line.text.Contains("ERROR") ).
  Dump("Matches found")
When debugging you can always use Skip() and Take() to reduce the number of lines searched.
A similar one but this uses a LinqPad HyperLinq object to use Notepad++ to open the file at the given line number.
// https://npp-user-manual.org/docs/command-prompt/
var notepadppPath = @"C:\Program Files (x86)\Tools\Notepad++\notepad++.exe";
Directory.EnumerateFiles(
   @"C:\Repos\",  // Directory
   "*.csproj", SearchOption.AllDirectories) // File names
   .SelectMany(file => File.ReadAllLines(file).Select((text, n) =>
		new
		{   
			file = new Hyperlinq(() => Process.Start(notepadppPath, 
				file+" -n"+(n+1).ToString()), file),
			lineNumber = n + 1,
			text
		}))
   .Where(x => // WHat you are looking for in the file
  // Regex.IsMatch(line.text, @"^.*tlpNotifySystemShutdown.*$"))
     x.text.Contains("DownloadProcess.Contracts") // 1.0.1
  || x.text.Contains("Foobar.Client")  // 13.15.0
  || x.text.Contains("DownloadProcess.Client") // 1.2.0
  || x.text.Contains("XxxZipCreator.")  // 5.1.0
  || x.text.Contains("Sloopy.Crial.Messages") // 1.6.3
   )
   .Dump("Matches found");
Here is another example:
Directory.EnumerateFiles(
  @"C:\Path\To\Search\Directory\",
  "*.cs", SearchOption.AllDirectories)
  .SelectMany(file => File.ReadAllLines(file).Select((text, n) => new { text, lineNumber = n + 1, file }))
  .Where(line => line.text.Contains("[CallerMemberName"))
  .Dump("Matches found")

No comments: