How restart the Console app?

2019-06-15 18:35发布

问题:

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

回答1:

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



回答2:

// Starts a new instance of the program itself
System.Diagnostics.Process.Start(Application.ExecutablePath);

// Closes the current process
Environment.Exit(0);


回答3:

static void Main(string[] args)
{
    var info = Console.ReadKey();
    if (info.Key == ConsoleKey.R)
    {
        var fileName = Assembly.GetExecutingAssembly().Location;
        System.Diagnostics.Process.Start(fileName);
    }
}


回答4:

Another simple way

//Start process, friendly name is something like MyApp.exe (from current bin directory)
System.Diagnostics.Process.Start(System.AppDomain.CurrentDomain.FriendlyName);

//Close the current process
Environment.Exit(0);


回答5:

I realize that this is 7 years old, but I just came across this. I think actually calling the executable and closing the current program is a bit of a cluge. As stated before, this is being over thought. I think that the cleanest and most modular way is to take everything that is in the Main method and make a different method, let's say Run() that contains everything that was in the Main method and then call the new Run() method from the Main method or wherever in the code it is desired to re-start the program.

So if the Main method looked like this:

static void Main(string[] args)
{
    /*
    Main Method Variable declarations;
    Main Method Method calls;
    Whatever else in the Main Method;
    */
    int SomeNumber = 0;
    string SomeString = default(string);

    SomeMethodCall();
    //etc.
}

Then just create a Run() method and put everything from Main into it, like so:

public static void Run()
{
    //Everything that was in the Main method previously

    /*
    Main Method Variable declarations;
    Main Method Method calls;
    Whatever else in the Main Method;
    */
    int SomeNumber = 0;
    string SomeString = default(string);

    SomeMethodCall();
    //etc.
}

Now that the Run() method is created and it has all the stuff that was in the Main method before, just make your main method like so:

static void Main(string[] args)
{
    Run();
}

Now, wherever in the code you want to "re-start" the program, just call the Run() method like so:

if(/*whatever condition is met*/)
{
    //do something first

    //then "re-start" the program by calling Run();
    Run();
}

So this is a look at the whole program simplified:

EDIT: When I posted this originally I didn't take into consideration any arguments that might have been passed to the program. To account for this four things need to be changed in my original answer.

  1. declare a global List<string> like this:

    public static List<string> MainMethodArgs = new List<string>();.

  2. In the Main method set the value of the MainMethodArgs list equal to the values passed into the Main method via args like this:

    MainMethodArgs = args.ToList();

  3. When creating the Run() method change the signature so that it expects a string[] called args to be passed to it like this:

    public static void Run(string[] args) { .... }

  4. Wherever in the program the Run() method is called, pass MainMethodArgs to Run() like this:

    Run(MainMethodArgs.ToArray());

I changed the example below to reflect these changes.

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExampleConsole
{
    class Program
    {
        public static List<string> MainMethodArgs = new List<string>();
        static void Main(string[] args)
        {
            MainMethodArgs = args.ToList();
            Run(MainMethodArgs.ToArray());
        }

        public static void Run(string[] args)
        {
            Console.WriteLine("Run() is starting");
            Console.ReadLine();
            //stuff that used to be in the public method
            int MainMethodSomeNumber = 0;
            string MainMethodSomeString = default(string);

            SomeMethod();
            //etc.
        }

        public static void SomeMethod()
        {
            Console.WriteLine("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...
                Run(MainMethodArgs.ToArray());
            }
        }
    }
}

In effect the program is "re-started" without having to re-run the executable and close the existing instance of the program. This seems a lot more "programmer like" to me.

Enjoy.



回答6:

Launch a second exe that ends the console program, starts a new instance, and ends itself?

be explicit, how is it in code?

This namespace should have everything you need, if that is a solution you want to pursue.

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx



回答7:

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
    }

}


回答8:

try like this:

// start new process
System.Diagnostics.Process.Start(
     Environment.GetCommandLineArgs()[0], 
     Environment.GetCommandLineArgs()[1]);

// close current process
Environment.Exit(0);


回答9:

//here the code to restart the console...
System.Diagnostics.Process.Start(Environment.GetCommandLineArgs()[0], Environment.GetCommandLineArgs().Length > 1 ? string.Join(" ", Environment.GetCommandLineArgs().Skip(1)) : null);