I have a server side logs folder that contains many hundreds of logs most of which are in subdirectories according to the machine the logs have come from. The task is to extract the full path of the latest file in each directory where the file contains a particular string (not all files have this string) so that analysis can be done per machine. I have included my attempt below but it seems rather clunky and long-winded and I wonder if there is an easier/better/faster/more efficient way of doing this maybe with linq?
void Main()
{
string SourcePath = @"L:\machinelogs";
string filemask = "*.log";
string searchitem = @"cannot access server data";
List<string> fileswithsearchitem = new List<string>();
DirectoryInfo directory = new DirectoryInfo(SourcePath);
IEnumerable<DirectoryInfo> dirs = directory.EnumerateDirectories("*",new EnumerationOptions() { RecurseSubdirectories = true, IgnoreInaccessible = true });
dirs.Append(directory);
foreach (var dir in dirs)
{
var found = false;
var files = dir.EnumerateFiles(filemask);
foreach(var file in files.OrderByDescending(f => f.CreationTime).ToList())
{
foreach (var line in File.ReadLines(file.FullName))
{
if(line.Contains(searchitem))
{
fileswithsearchitem.Add(file.FullName + " : " + line);
found = true;
break;
}
}
if(found)
{
break;
}
}
}
foreach (string item in fileswithsearchitem)
{
Console.WriteLine(item);
}
}
```