How restart the Console app?

2019-06-15 18:57发布

I need to restart the app Console when the user press "R".

I have this

Console.WriteLine(message, "Rebuild Log Files" 
    + " Press Enter to finish, or R to restar the program...");
string restar = Console.ReadLine();
if(restar.ToUpper() == "R")
{
   //here the code to restart the console...
}

thanks

9条回答
爷、活的狠高调
2楼-- · 2019-06-15 19:36
static void Main(string[] args)
{
    var info = Console.ReadKey();
    if (info.Key == ConsoleKey.R)
    {
        var fileName = Assembly.GetExecutingAssembly().Location;
        System.Diagnostics.Process.Start(fileName);
    }
}
查看更多
倾城 Initia
3楼-- · 2019-06-15 19:37

I don't think you really need restart whole app. Just run required method(s) after pressing R. No need to restart.

查看更多
闹够了就滚
4楼-- · 2019-06-15 19:37

Everybody is over-thinking this. Try something like this:

class Program : IDisposable
{

    class RestartException : Exception
    {
        public RestartException() : base()
        {
        }
        public RestartException( string message ) : base(message)
        {
        }
        public RestartException( string message , Exception innerException) : base( message , innerException )
        {
        }
        protected RestartException( SerializationInfo info , StreamingContext context ) : base( info , context )
        {
        }
    }

    static int Main( string[] argv )
    {
        int  rc                      ;
        bool restartExceptionThrown ;

        do
        {
            restartExceptionThrown = false ;
            try
            {
                using ( Program appInstance = new Program( argv ) )
                {
                    rc = appInstance.Execute() ;
                }
            }
            catch ( RestartException )
            {
                restartExceptionThrown = true ;
            }
        } while ( restartExceptionThrown ) ;
        return rc ;
    }

    public Program( string[] argv )
    {
        // initialization logic here
    }

    public int Execute()
    {
        // core of your program here
        DoSomething() ;
        if ( restartNeeded )
        {
            throw new RestartException() ;
        }
        DoSomethingMore() ;
        return applicationStatus ;
    }

    public void Dispose()
    {
        // dispose of any resources used by this instance
    }

}
查看更多
登录 后发表回答