简体   繁体   中英

How to restart dotnetcore 2 C# Console app

How should I restart a dotnetcore C# console app?

I have tried suggestions found for C# console apps, but doesnt work for dotnetcore.

(This is not asp.net, which is where so many dotnetcore answers point)

OK, so im going to assume in this answer that it is ok with you if your program will start a new instance of your program and then close itself.

Here we go:

Since a dotnet console app can be started from the console, I think the best way to start a new instance of your console application would be thorugh using shell commands. To run shell commands from your program, add this helper class to your application: (If you are using windows instead of mac/linux, please see the end of this post)

  using System;
  using System.Diagnostics;
public static class ShellHelper
{
    public static string Shell(this string cmd)
    {
        var escapedArgs = cmd.Replace("\"", "\\\"");

        var process = new Process()
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "/bin/bash",
                Arguments = $"-c \"{escapedArgs}\"",
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
            }
        };
        process.Start();
        string result = process.StandardOutput.ReadToEnd();
        process.WaitForExit();
        return result;
    }
}

Then since this is a extension method, just import it and then create a string with the command to restart your app and then use the Shell() method.

So if you are in development and you normally start your app by running dotnet run then make sure you are in the proper directory and then just use this line of code "dotnet run".Shell();

If you want to get the feedback from running the command then just assign the return value like this string result = "dotnet run".Shell();

Then once you have started the new process you just exit your current program by either returning on your main method etc.

Please Note: The above code is for mac/linux, If you are on windows, then the following two lines of the above code:

FileName = "/bin/bash",
Arguments = $"-c \"{escapedArgs}\"",

Should be replaced with:

FileName = "cmd.exe",
Arguments = $"/c \"{escapedArgs}\"",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM