-1

How can i reboot my C# console application like in Java when programm still work in same console, without creating new one.

I tried to start new application with Process.UseShellExecute = false and kill current process from newly created, but i can kill parent process from child using this. I tried to kill current process after creating new, but also it doesnt work.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
Robert
  • 507
  • 2
  • 9
  • 20

1 Answers1

0

There is no straightforward way to do this, however you can simulate this behavior:

  1. Change your application from console application to Windows application.
  2. Create a console for the first instance of your application
  3. Start a new instance of your application and attach to the console created in step 2.
  4. Exit the first instance.

It is important not to forget to change the application type to Windows application.

The following code will restart the application until you press Ctrl+C:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;

class Program
{
    [DllImport("kernel32", SetLastError = true)]
    static extern bool AllocConsole();

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool AttachConsole(uint dwProcessId);

    const uint ATTACH_PARENT_PROCESS = 0x0ffffffff;


    [STAThread]
    static void Main(string[] args)
    {
        if (!AttachConsole(ATTACH_PARENT_PROCESS))
        {
            AllocConsole(); 
        }
        Console.WriteLine("This is process {0}, press a key to restart within the same console...", Process.GetCurrentProcess().Id);
        Console.ReadKey(true);

        // reboot application
        var process = Process.Start(Assembly.GetExecutingAssembly().Location);

        // wait till the new instance is ready, then exit
        process.WaitForInputIdle();
    }
}
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
  • what about Mono, this won't work with mono, there is no way to do this without using windows kernel libs? – Robert Jul 02 '12 at 22:11
  • 1
    @Robert: Are you on a non-Windows platform? If so, on which platform? And please don't leave out such relevant bits of information from your question. – Dirk Vollmar Jul 02 '12 at 22:37