如何重新启动Console应用程序?

ale*_*ale 11 c# console console-application

当用户按"R"时,我需要重新启动应用控制台.

我有这个

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...
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Jep*_*sen 12

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

// Closes the current process
Environment.Exit(0);
Run Code Online (Sandbox Code Playgroud)

  • 抱歉,我忘记它是一个控制台应用程序 - 应用程序是Windows窗体命名空间的一部分,而是使用环境(我更新了代码) (2认同)

Sea*_*ron 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*cek 5

我不认为你真的需要重启整个应用程序.按下R后只需运行所需的方法.无需重启.

  • 我不完全同意“我认为你真的不需要重新启动整个应用程序”。您真正需要的情况之一是,如果您有动态加载的程序集并且想要删除它们,因为显然 AppDomain 中没有程序集卸载功能。 (2认同)

Iva*_*nF. 5

另一种简单的方法

//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);
Run Code Online (Sandbox Code Playgroud)