Home   Cover Cover Cover Cover
 

Gleichnamige Typen aus verschiedenen Namensräumen

AsyncSearch.cs
/* Asynchrone Suche in Textdateien
   Es sollen alle C#-Dateien eines Verzeichnisses gelistet werden,
   die einen bestimmten Suchstring enthalten. Das Lesen der Dateien
   soll asynchron zum Suchen erfolgen. Der Name des zu durchsuchenden
   Verzeichnisses wird als Kommandozeilenargument uebergeben.
   
   Aufruf: AsyncSearch directoryName searchPattern
------------------------------------------------------------*/
using System;
using System.IO;
using System.Threading.Tasks;


public class AsyncSearch {
  
  static async Task SearchFilesAsync(string dirName, FileInfo[] files, string pattern) {
    Console.WriteLine("Files in " + dirName + " containing '" + pattern + "'");
    foreach (FileInfo file in files) {
      StreamReader r = new StreamReader(file.FullName);
      string s = await r.ReadToEndAsync();
      if (s.IndexOf(pattern) >= 0){
        Console.WriteLine("  " + file.Name);
      }
    }
  }
  
  public static void Main(string[] arg) {
    if (arg.Length == 2) {
      try {
        //-- get the names of all files in the directory
        DirectoryInfo dir = new DirectoryInfo(arg[0]);
        FileInfo[] files = dir.GetFiles("*.cs");
        //-- start reading and searching the files;
        //-- must be a separate method because Main() must not be async
        Task t = SearchFilesAsync(arg[0], files, arg[1]);
        //-- wait for the task to complete;
        //-- all started subtasks run in background threads that would be
        //-- terminated if Main() reaches its end
        t.Wait();
      } catch (ArgumentException) {
        Console.WriteLine("-- invalid directory name");
      }
    } else {
      Console.WriteLine("-- Synopsis: AsyncSearch directoryName searchPattern");
    }
  }
}