18

我想使用重新启动功能来构建我的应用程序。我在代码项目上找到

ProcessStartInfo Info=new ProcessStartInfo();
Info.Arguments="/C choice /C Y /N /D Y /T 3 & Del "+
               Application.ExecutablePath;
Info.WindowStyle=ProcessWindowStyle.Hidden;
Info.CreateNoWindow=true;
Info.FileName="cmd.exe";
Process.Start(Info); 
Application.Exit();

这根本不起作用......另一个问题是,如何重新启动它?也许也有启动应用程序的参数。

编辑:

http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=31454&av=58703
4

10 回答 10

46

我使用与您在重新启动应用程序时尝试的代码类似的代码。我发送一个定时 cmd 命令来为我重新启动应用程序,如下所示:

ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C ping 127.0.0.1 -n 2 && \"" + Application.ExecutablePath + "\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
Application.Exit(); 

该命令被发送到操作系统,ping 暂停脚本 2-3 秒,此时应用程序已退出Application.Exit(),然后 ping 后的下一个命令再次启动它。

注意:\"路径周围的 puts 引号,以防它有空格,没有引号 cmd 无法处理。

希望这可以帮助!

于 2012-03-08T09:54:34.100 回答
29

为什么不使用

Application.Restart();

??

更多关于重启

于 2012-03-07T15:15:28.023 回答
9

为什么不只是以下?

Process.Start(Application.ExecutablePath); 
Application.Exit();

如果您想确保应用程序不会运行两次,要么使用Environment.Exit(-1)立即终止进程(不是真正的好方法),要么使用类似启动第二个应用程序的方法,它检查主应用程序的进程并再次启动它过程消失了。

于 2012-03-07T15:10:41.697 回答
6

你有初始应用程序A,你想重新启动。所以,当你想杀死 A 时,启动一个小应用程序 B,B 杀死 A,然后 B 启动 A,然后杀死 B。

要启动一个进程:

Process.Start("A.exe");

要杀死一个进程,是这样的

Process[] procs = Process.GetProcessesByName("B");

foreach (Process proc in procs)
   proc.Kill();
于 2012-03-07T15:18:03.653 回答
3

很多人建议使用 Application.Restart。实际上,此功能很少按预期执行。我从来没有关闭过我调用它的应用程序。我一直不得不通过其他方法关闭应用程序,例如关闭主窗体。

你有两种处理方法。您要么有一个外部程序来关闭调用进程并启动一个新进程,

或者,

如果将参数作为重新启动传递,则您的新软件启动会杀死同一应用程序的其他实例。

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            try
            {
                if (e.Args.Length > 0)
                {
                    foreach (string arg in e.Args)
                    {
                        if (arg == "-restart")
                        {
                            // WaitForConnection.exe
                            foreach (Process p in Process.GetProcesses())
                            {
                                // In case we get Access Denied
                                try
                                {
                                    if (p.MainModule.FileName.ToLower().EndsWith("yourapp.exe"))
                                    {
                                        p.Kill();
                                        p.WaitForExit();
                                        break;
                                    }
                                }
                                catch
                                { }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
于 2012-03-07T15:45:47.353 回答
2

Another way of doing this which feels a little cleaner than these solutions is to run a batch file which includes a specific delay to wait for the current application to terminate. This has the added benefit of preventing the two application instances from being open at the same time.

Example windows batch file ("restart.bat"):

sleep 5
start "" "C:\Dev\MyApplication.exe"

In the application, add this code:

// Launch the restart batch file
Process.Start(@"C:\Dev\restart.bat");

// Close the current application (for WPF case)
Application.Current.MainWindow.Close();

// Close the current application (for WinForms case)
Application.Exit();
于 2012-05-15T02:32:17.877 回答
2

Winforms 有Application.Restart()方法,它就是这样做的。如果您使用的是 WPF,您可以简单地添加对它的引用System.Windows.Forms并调用它。

于 2012-03-07T15:16:31.740 回答
1

我的解决方案:

        private static bool _exiting;
    private static readonly object SynchObj = new object();

        public static void ApplicationRestart(params string[] commandLine)
    {
        lock (SynchObj)
        {
            if (Assembly.GetEntryAssembly() == null)
            {
                throw new NotSupportedException("RestartNotSupported");
            }

            if (_exiting)
            {
                return;
            }

            _exiting = true;

            if (Environment.OSVersion.Version.Major < 6)
            {
                return;
            }

            bool cancelExit = true;

            try
            {
                List<Form> openForms = Application.OpenForms.OfType<Form>().ToList();

                for (int i = openForms.Count - 1; i >= 0; i--)
                {
                    Form f = openForms[i];

                    if (f.InvokeRequired)
                    {
                        f.Invoke(new MethodInvoker(() =>
                        {
                            f.FormClosing += (sender, args) => cancelExit = args.Cancel;
                            f.Close();
                        }));
                    }
                    else
                    {
                        f.FormClosing += (sender, args) => cancelExit = args.Cancel;
                        f.Close();
                    }

                    if (cancelExit) break;
                }

                if (cancelExit) return;

                Process.Start(new ProcessStartInfo
                {
                    UseShellExecute = true,
                    WorkingDirectory = Environment.CurrentDirectory,
                    FileName = Application.ExecutablePath,
                    Arguments = commandLine.Length > 0 ? string.Join(" ", commandLine) : string.Empty
                });

                Application.Exit();
            }
            finally
            {
                _exiting = false;
            }
        }
    }
于 2016-07-04T21:41:53.140 回答
1

这对我有用:

Process.Start(Process.GetCurrentProcess().MainModule.FileName);
Application.Current.Shutdown();

其他一些答案有一些巧妙的东西,比如等待 aping给初始应用程序时间来结束,但如果你只需要一些简单的东西,这很好。

于 2020-11-16T22:05:20.003 回答
0

对于 .Net 应用程序解决方案如下所示:

System.Web.HttpRuntime.UnloadAppDomain()

在 myconfig 文件中更改 AppSettings 后,我使用它来重新启动我的 Web 应用程序。

System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
configuration.AppSettings.Settings["SiteMode"].Value = model.SiteMode.ToString();
configuration.Save();
于 2016-08-17T10:47:46.663 回答