I am just learning C#

how to clear a cmd line after wrong entry like wrong user name or password in C sharp?

my codes here, have a look thanks
----------------------------------------

using System;
using System.Collections.Generic;
using System.Text;

namespace DisplayLogin
{
    class Program
    {
       
        static void Main()
        {


            Console.WriteLine("________________________________________________");
            Console.WriteLine("");
            {
                AdminName();
            }
            Console.WriteLine("");
            
        }
        static void AdminName()
        {
            Console.Write("\tAdmin name:");
            string adminName = Console.ReadLine();

            if (adminName == "user")
            {
                Console.WriteLine("");
                PassWord();
            }
            else
            {

                Console.WriteLine(""); 
                Console.WriteLine("\tInvalid Entry! Try again");//I need to clear all previous entry
                Console.WriteLine("");
                AdminName();
            }

        }

        static void PassWord()
        {
            Console.Write("\tPassword:");
            string passWord = Console.ReadLine();
            if (passWord == "123456")
            {
                Console.WriteLine("");


                Console.WriteLine("________________________________________________");
                Console.WriteLine("");

                //CreateAccount();
            }
            else
            {

                Console.WriteLine("");
                Console.WriteLine("\tInvalid Password! Try again");//I need to clear all previous entry
                Console.WriteLine("");
                PassWord();
            }
        }

        
    }
}

Dani AI

Generated

Nice question, . Two quick additions that build on ’s simple screen clear and ’s loop-based flow:

  • If you only want to erase the last attempt (not the whole screen), clear that specific console line and redraw the prompt. This keeps context on the screen and feels less jarring than Console.Clear().
static void ClearLine(int line)
{
    int t = Console.CursorTop;
    Console.SetCursorPosition(0, line);
    Console.Write(new string(' ', Console.BufferWidth));
    Console.SetCursorPosition(0, t);
}

// usage
int promptTop = Console.CursorTop;
Console.Write("User: ");
string user = Console.ReadLine();
if (!ValidUser(user))
{
    Console.WriteLine("Invalid username");
    Console.ReadKey();
    ClearLine(promptTop);                  // wipe "User: ..." + entry
    Console.SetCursorPosition(0, promptTop);
    // re-prompt here
}
  • Do not echo passwords with ReadLine(). Read keys, mask with *, and support backspace. Pair this with a loop (as suggested) rather than recursion to avoid stack growth on many failures.
static string ReadPassword()
{
    var sb = new System.Text.StringBuilder();
    while (true)
    {
        var k = Console.ReadKey(true);
        if (k.Key == ConsoleKey.Enter) { Console.WriteLine(); break; }
        if (k.Key == ConsoleKey.Backspace && sb.Length > 0) { sb.Length--; Console.Write("\b \b"); }
        else if (!char.IsControl(k.KeyChar)) { sb.Append(k.KeyChar); Console.Write('*'); }
    }
    return sb.ToString();
}

Tip: Console.SetCursorPosition can throw if output is redirected; if you might pipe output, guard with if (!Console.IsOutputRedirected) or catch exceptions and fall back to Console.Clear().

Recommended Answers

All 8 Replies

Console.Clear();

here a complete example :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("some stuff");
            Console.ReadLine();
            Console.WriteLine("some more stuff");
            Console.ReadLine();
            Console.Clear();
        }
    }
}

Try this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace daniweb.console
{
  class Program
  {
    static void Main(string[] args)
    {
      bool loggedIn = default(bool);
      while (!loggedIn)
      {
        string userName = GetUserName(); //only returns if successful
        string password = GetPassword();
        loggedIn = ValidPassword(userName, password);
        if (!loggedIn)
        {
          Console.WriteLine("Invalid password");
          Console.WriteLine(string.Empty);
          Console.WriteLine("Press any key to continue");
          Console.ReadKey();
          Console.Clear();
        }
      }

      throw new NotImplementedException("They are logged in at this point");
    }

    static string GetUserName()
    {
      string res = default(string);
      while (!ValidUser(res))
      {
        if (res != null)
        {
          Console.WriteLine("Invalid username");
          Console.WriteLine(string.Empty);
          Console.WriteLine("Please any key to continue");
          Console.ReadKey();
          Console.Clear();
        }
        Console.Write("User: ");
        res = Console.ReadLine();
      }
      return res;
    }

    static string GetPassword()
    {
      string res = default(string);
      Console.Write("Password: ");
      res = Console.ReadLine();
      return res;
    }

    static bool ValidUser(string UserName)
    {
      return (string.Compare(UserName, "admin", true) == 0);
    }

    static bool ValidPassword(string UserName, string Password)
    {
      if (string.Compare(UserName, "admin", true) == 0)
        return (string.Compare(Password, "123456", true) == 0);
      else
        return false;
    }

  }
}

Thanks a lot friends, 'Sknake's' I will try your program tomorrow,,,now so sleepy. It seems I can use your code,,,,is it okey??? .....Thanks in advance.
Xavier

what about mine? didnt it work?

Hi Serkan Sendur, yours is good and simple,I tried and working. I just haven't tried the other one need time to understand. Thanks bro.

I tried both very good, Thanks a lot for prompt help!!!!
Xavier

dont forget, the shorter is the better(sknake just likes writing code too much ;))
And please mark this thread as saved.

dont forget, the shorter is the better(sknake just likes writing code too much ;))
And please mark this thread as saved.

:P
Sometimes I get a little bored and need things to do... what can I say.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.