Refactoring: counting all lines in all files in a given folder

I wrote code to count the number of lines in all files in a given folder. It works great, but I'm trying to incorporate all the possible features of C # to reorganize it into more compact and efficient code. Please help me do this.

Here is the code.

class LineNumberCounter { public static string Calculate(string folderPath, string pattern = "*.txt") { DirectoryInfo dirInfo = new DirectoryInfo(folderPath.Trim()); if (!dirInfo.Exists) throw new ArgumentException("No such directory exists"); StringBuilder returnValue = new StringBuilder(); long totalLines = 0; pattern.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).All(filter => { int count = 0; dirInfo.GetFiles(filter.Trim(), SearchOption.AllDirectories).All(file => { using (StreamReader reader = file.OpenText()) { for (; reader.Peek() > -1; count++) reader.ReadLine(); } returnValue.AppendLine(string.Format("Number of lines with {0} pattern is {1}", filter, count)); totalLines += count; return true; } ); return true; }); //foreach (string filter in // pattern.Split(new char[] { ';' }, // StringSplitOptions.RemoveEmptyEntries)) //{ // FileInfo[] files = dirInfo.GetFiles(filter.Trim(), // SearchOption.AllDirectories); // int count = 0; // Array.ForEach<FileInfo>(files, file => // { // using (StreamReader reader = file.OpenText()) // { // for (; reader.Peek() > -1; count++) // reader.ReadLine(); // } // }); // returnValue.AppendLine(string.Format("Number of lines with {0} pattern is {1}", // filter, count)); // totalLines += count; //} returnValue.AppendLine(); returnValue.AppendLine("Total Lines = " + totalLines); return returnValue.ToString(); } } 

The commented lines were the ones I originally wrote. I tried to reorganize it. But still want to check if it has more features.

+4
source share
2 answers

Using the new method >=.NET 4 File.ReadLines ()

 int total = File.GetFiles(folderPath, pattern) .Sum(x => File.ReadLines(x).Count()); 

Some considerations from MSDN :

The ReadLines and ReadAllLines methods differ as follows: when you use ReadLines, you can start enumerating a collection of strings before the entire collection is returned; when you use ReadAllLines, you must wait until the entire array of strings is returned before you can access the array. Therefore , when you work with very large files, ReadLines may be more efficient .

+10
source
 foreach (var filePath in Directory.GetFiles(folderPath, pattern(//standard pattern), SearchOption.AllDirectories)) { var count=File.OpenText(filePath).ReadAllLines().Count(); returnValue.AppendLine(string.Format("Number of lines with {0} pattern is {1}", Path.GetExtension(filePath), count)); } 
+1
source

Source: https://habr.com/ru/post/1387761/


All Articles