Leon Newswanger
Leon Newswanger

Reputation: 617

Catch when Console.CursorTop hits a location

I'm writing a recursive method that searches for files and when it hits a match it prints the full path to the console window. Obviously, if this returns a lot of results it will quickly fill the screen not providing adequate time to review the results. I would like a method of catching when the console's CursorLeft property hits a certain position to insert ReadKey() to allow reviewing of the results. My search method is as follows

static void FileSearch(string Base, string Pattern)
{
    if (!Directory.Exists(Base)) return;

    string _Patt = Pattern.ToLower();

    var Files = Directory.GetFiles(Base).Where(File 
        => Path.GetFileName(File).ToLower().Contains(_Patt));

    foreach (string File in Files)
        Console.WriteLine(File);

    string[] Dirs = Directory.GetDirectories(Base);

    foreach (string Dir in Dirs)
        FileSearch(Dir, Pattern);
}

I'm aware that I could add some sort of indexer, like an incrementing int, to keep track of the position and check it with each iteration of the loop, and that int could be passed as a ref so that all calls are looking at the same int. I'm also aware that with each iteration I could simply check the current position. I'm just wondering if there would be a cleaner way to accomplish this, perhaps something similar to event handling?

Upvotes: 0

Views: 258

Answers (1)

Sina Iravanian
Sina Iravanian

Reputation: 16286

I think Console.CursorTop is the right property to look at. Check for the following after printing each line:

if (Console.CursorTop % (Console.WindowHeight - 1) == 0)
    Console.ReadKey();

as in:

static void FileSearch(string Base, string Pattern)
{
    if (!Directory.Exists(Base)) return;

    string _Patt = Pattern.ToLower();

    var Files = Directory.GetFiles(Base).Where(File 
        => Path.GetFileName(File).ToLower().Contains(_Patt));

    foreach (string File in Files)
    {
        Console.WriteLine(File);
        if (Console.CursorTop % (Console.WindowHeight - 1) == 0)
            Console.ReadKey();
    }

    string[] Dirs = Directory.GetDirectories(Base);

    foreach (string Dir in Dirs)
        FileSearch(Dir, Pattern);
}

Upvotes: 1

Related Questions