[dba-VB] C# programming exercises in LINQPad: Sample 2 - looking for a text string in code files

Gustav Brock gustav at cactus.dk
Sat Jun 23 12:18:49 CDT 2012


Hi Shamil

I just tested this in LINQPad and it runs fine. Could be very useful.

/gustav


>>> Salakhetdinov Shamil <mcp2004 at mail.ru> 19-06-12 22:14 >>>
Hi All --

Here is a code snippet  from my LINQPad utility code snippets collection to look for a text string in all the files of a directory (including subdirectories) 
I know there exists a grep (but I can't find it here on my system) utility or windows explorer advanced search but the sample code (see P.S.) seems to be working much quicker(?),
also this code snippets is not a bad example of modern C# development techniques - try:

Here are the results for my real life case - I have just needed to find a text in 3765  .cs files.

1. first run took 30 seconds
start: 19.06.2012 23:36:06 
end:  19.06.2012 23:36:34 

 2. subsequent runs
Total files count 
3765 

Start Time 
19.06.2012 23:59:39 

e:\projects\code\TestSolution\Test.BLL\Reports Import\TestApiAgent.cs
e:\projects\code\TestSolution\Test.Core\Settings\General Settings\GeneralSettings.cs

Total files length 
39905062 

End Time 
19.06.2012 23:59:42 

Elapsed time (ms) 
2483.1421 

Processing speed (chars/ms) 
16070.3900111073 

Thank you.

-- Shamil

P.S. Code snippet

// Search for a text string in all the *.cs files of a directory
// including its subdirectories
//

// folder to search code files in
string folderName = @"e:\projects\code";
// search string
string searchFor = "test.com";

var folder = new System.IO.DirectoryInfo(folderName);
var files = folder.GetFiles("*.cs", SearchOption.AllDirectories);

files.Length.Dump("Total files count"); 

var startTime = DateTime.Now;  
startTime.Dump("Start Time"); 

int totalLength = 0;
files.AsParallel().ForAll(x => 
{
  Interlocked.Add(ref totalLength,   
    (int)(new System.IO.FileInfo(x.FullName)).Length);  
  string code = System.IO.File.ReadAllText(x.FullName, Encoding.UTF8);
  if (code.IndexOf(searchFor,StringComparison.InvariantCultureIgnoreCase)>-1)
    System.Console.WriteLine(x.FullName);   
});


totalLength.Dump("Total files length");
var endTime = DateTime.Now;  
endTime.Dump("End Time"); 

(endTime - startTime).TotalMilliseconds.Dump("Elapsed time (ms)");
(totalLength / (endTime - startTime).TotalMilliseconds).Dump("Processing speed (chars/ms)");  



More information about the dba-VB mailing list