C# console prompt example

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

namespace ConsolePromptExample
{
    class Program
    {
        bool exit = false;

        static void Main(string[] args)
        {
            Program program = new Program();
            program.Start();
        }

        public void Start()
        {
            // do some stuff
            // SomeObject someObjet = new SomeObject();
            // someObjet.Initialize();

            while (exit == false)
            {
                RunCommand(Prompt());
            }
        }

        public void RunCommand(string command)
        {
            switch (command.Contains(" ")
                   ? command.Split(' ')[0].ToLower()
                   : command.ToLower())
            {
                case "x":
                case "q":
                case "quit":
                case "exit":
                    exit = true;
                    return;

                case "scan":

                    Console.WriteLine("scan done");
                    break;

                case "?":
                case "help":
                    PrintHelp();
                    break;

                default:
                    Console.WriteLine("I didn't get that ...");
                    break;
            }
        }

        public void PrintHelp()
        {
            string helpFile = "help.txt";
            string WorkingDirectory = Directory.GetCurrentDirectory().Replace("bin\\Debug", string.Empty);
            string file = string.Format("{0}\\{1}", WorkingDirectory, helpFile);

            using (StreamReader r = new StreamReader(File.OpenRead(file)))
            {
                while (r.Peek() > -1)
                {
                    Console.WriteLine(r.ReadLine());
                }
                Console.WriteLine();
            }
        }

        public string Prompt()
        {
            Console.Write("what's next >");
            return Console.ReadLine();
        }
    }
}

DOWNLOAD example

Leave a Reply

Your email address will not be published. Required fields are marked *