Thursday, October 20, 2016

Two cool techniques

It's been a while since my last post. I guess I haven't been struggling to solve problems like I used to. Today I had a couple of problems to solve that have nothing to do with WPF.

The scenario is that I have log files accumulated on the middle tier and I want to be able to search them. I want to be able to give the user either a list of all log files that match a file name, or a list of log files that match a file name and contain a specified string.

There is a method called GetFiles on the DirectoryInfo class that returns a list of FileInfo objects for files that match a particular filter. I used the LINQ Select method to return the FullName property from each of those FileInfo objects into a collection of strings.

Imports System.Linq
Dim NameFilter as String = "*BOB*"
Dim LogPath as String = "C:\Logs"
Dim ReturnFiles As New Collections.Generic.List(Of String)
ReturnFiles.AddRange(New IO.DirectoryInfo(LogPath).GetFiles(NameFilter).Select(Function(t) t.FullName))

The other requirement is to select files that contain a specific string. Now I could do this by reading and searching each file, but the FindInFiles method is much faster as well as being cooler.

Imports System.Linq
Dim NameFilter as String = "*BOB*"
Dim LogPath as String = "C:\Logs"
Dim ContentFilter as String = "contains"
Dim ReturnFiles As New Collections.Generic.List(Of String)
ReturnFiles.AddRange(Microsoft.VisualBasic.FileIO.FileSystem.FindInFiles(LogPath, ContentFilter, True, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, NameFilter))