13

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

Sergi Papaseit
  • 15,999
  • 16
  • 67
  • 101
ale
  • 3,301
  • 10
  • 40
  • 48
  • 1
    Launch a second exe that ends the console program, starts a new instance, and ends itself? – asawyer Apr 18 '11 at 17:23
  • be explicit, how is it in code? – ale Apr 18 '11 at 17:26
  • What does "restart the app Console" mean? – Gabe Apr 18 '11 at 17:28
  • I think you want to restart the program, but that you don't really mind about the Console (the window that hosts your console program). Right? – CharlesB Apr 18 '11 at 17:28
  • yes, all again, since the begin, start the console window and start the process.. – ale Apr 18 '11 at 17:31
  • @ale I understand for the program, but I think you don't care about restarting the console window. Or tell us why if you do. – CharlesB Apr 18 '11 at 17:32
  • I found a better solution here: [better stackoverflow solution](https://stackoverflow.com/questions/24343090/system-windows-forms-application-does-not-contain-a-definition-for-executablep) – pianocomposer Feb 14 '23 at 16:04

10 Answers10

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

// Closes the current process
Environment.Exit(0);
  • 2
    Sorry, I forgot it was a console application - Application is a part of the Windows Forms namespace, instead use Environment (I updated the code) – Jeppe Andersen Apr 18 '11 at 17:35
  • Also, the integer 0 indicates a clean exit to the system, [link](http://msdn.microsoft.com/en-us/library/ms681382%28VS.85%29.aspx) heres a list of others if you are interested – Jeppe Andersen Apr 18 '11 at 17:37
  • the point is: when occur an exception I wan to restart all the process or start the Main method, since this other method: public void DisplayMessage(string message) { Console.WriteLine(message, "Rebuild Log Files"); Console.WriteLine(" Press Enter to finish, or R to restar the program..."); string restart = Console.ReadLine(); if(restart.ToUpper() == "R") { //Call the Main method or restar the app } Console.ReadKey(); } – ale Apr 18 '11 at 17:55
8
static void Main(string[] args)
{
    var info = Console.ReadKey();
    if (info.Key == ConsoleKey.R)
    {
        var fileName = Assembly.GetExecutingAssembly().Location;
        System.Diagnostics.Process.Start(fileName);
    }
}
Sean Kearon
  • 10,987
  • 13
  • 77
  • 93
6

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

Tomas Voracek
  • 5,886
  • 1
  • 25
  • 41
  • 1
    ok, so, in this case I need to call the method: public static void Main(string[] args){}, how can I call it? – ale Apr 18 '11 at 17:42
  • I do not know what methods/program flow is in your program but you can always extract code, method calls from Main... – Tomas Voracek Apr 18 '11 at 17:44
  • +1 @ale you should have been more clear in your question, I imagine this is what you really wanted. – asawyer Apr 18 '11 at 18:12
  • 2
    I don't fully agree with the "I don't think you really need restart whole app." One of those cases when you really need is if you have dynamically loaded assemblies and you want to get rid of them, because obviously there's no assembly unload feature in AppDomain. – Visar Feb 03 '17 at 23:55
  • @Visar Obviously it is not this case. – Tomas Voracek May 20 '18 at 13:00
  • @ale , This is the right methodology in my opinion. I just entered an answer that goes over it more in depth. – Gharbad The Weak Dec 13 '18 at 06:09
5

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);
IvanF.
  • 513
  • 10
  • 18
4

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.

Gharbad The Weak
  • 1,541
  • 1
  • 17
  • 39
  • "in effect", but not really. If assemblies have been updated they don't get reloaded and static variables and caches are not cleared. A common "restart" scenario is to load updated assemblies. – Garr Godfrey Dec 23 '21 at 21:23
0

try like this:

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

// close current process
Environment.Exit(0);
Fabio
  • 1
0

Ended up with something like this.

#if DEBUG
Process.Start("dotnet", Environment.GetCommandLineArgs().Prepend("run").Take(2));
#else
Process.Start(Environment.CommandLine);
#endif
Quit.ConsoleShutdown(null, null);

I'm sure this specific line: Process.Start("dotnet", Environment.GetCommandLineArgs().Prepend("run").Take(2)); can be improved on though, since it looks a bit confusing at first glance.

Lunar
  • 480
  • 4
  • 11
-1
//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);
the
  • 1
  • 2
-1

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

asawyer
  • 17,642
  • 8
  • 59
  • 87
  • the point is: when occur an exception I wan to restart all the process or start the Main method, since this other method: public void DisplayMessage(string message) { Console.WriteLine(message, "Rebuild Log Files"); Console.WriteLine(" Press Enter to finish, or R to restar the program..."); string restart = Console.ReadLine(); if(restart.ToUpper() == "R") { //Call the Main method or restar the app } Console.ReadKey(); } – ale Apr 18 '11 at 17:57
-2

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
    }

}
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • 16
    Overthinking your answer while starting by claiming everyone is overthinking the solution, what a gem. – Oli4 Jan 17 '17 at 05:37