1

I have a small .NET console program that asks for SQL credentials (login, password). The problem is that if I key Ctrl-C during login prompt (string userId = Console.ReadLine(); below), the program stops but "password:" prompt is written to the console. Relevant fragment:

Console.Write("login: ");
string userId = Console.ReadLine();
    
Console.Write("password: ");

Output on Ctrl-C during login prompt:

login: password:

How can I avoid executing subsequent the Console.Write("password: "); after exiting with Ctrl-C?

UPDATE 1: CancelKeyPress event handler doesn't help. At least for me, it works for Console.ReadKey, but not for Console.ReadLine: password prompt is still written.

UPDATE 2: If there is Write/WriteLine after null-check block, it's still executed on my machine (Win10, VS2019). So, the question in fact remains. Current workaround - ReadKey.

guest
  • 25
  • 6
  • Does this answer your question? [How do I trap ctrl-c (SIGINT) in a C# console app](https://stackoverflow.com/questions/177856/how-do-i-trap-ctrl-c-sigint-in-a-c-sharp-console-app) – Kraego Sep 13 '21 at 18:39
  • @kraego No. I added a note to question about it. – guest Sep 18 '21 at 13:38
  • I ran this code on my machine and the process exits immediately after I press **Ctrl-C**. – AgentFire Sep 18 '21 at 17:30

2 Answers2

0

As AgentFire mentioned add input validation.

    class Program
    {
        static void Main()
        {
            Console.Write("login: ");
            string userId = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(userId))
            {
                Environment.Exit(-1);
            }
            Console.Write("password: ");
            ....
        }

    }
Kraego
  • 2,978
  • 2
  • 22
  • 34
  • Thank you, but Write after check still executes for me (added a note). Apparently, I'll move on with ReadKey. – guest Sep 19 '21 at 17:00
  • One way, could be to invert the logic as i did in the edit of my answer - end program when input is null or empty (maybe not so good for diagnostics). Or add checks for all inputs, or as you mentioned use ReadKey .... – Kraego Sep 19 '21 at 17:24
0

If your code indeed continues to run after you press Ctrl-C (which it doesn't on my machine for some reason), I would bet ten bucks that your userId variable would be null, instead of the usual empty string (if you input nothing and press Enter).

So, just check for null.

AgentFire
  • 8,944
  • 8
  • 43
  • 90
  • Thank you, but Write after check still executes for me (added a note). Apparently, I'll move on with ReadKey. – guest Sep 19 '21 at 17:01