C# 自行重启应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9603926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restart an application by itself
提问by Noli
I want to build my application with the function to restart itself. I found on codeproject
我想使用重新启动功能来构建我的应用程序。我在 codeproject 上找到的
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();
This does not work at all... And the other problem is, how to start it again like this? Maybe there are also arguments to start applications.
这根本不起作用......另一个问题是,如何像这样再次启动它?也许也有启动应用程序的争论。
Edit:
编辑:
http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=31454&av=58703
采纳答案by Bali C
I use similar code to the code you tried when restarting apps. I send a timed cmd command to restart the app for me like this:
我使用与您在重新启动应用程序时尝试的代码类似的代码。我发送一个定时 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();
The command is sent to the OS, the ping pauses the script for 2-3 seconds, by which time the application has exited from Application.Exit(), then the next command after the ping starts it again.
命令被发送到操作系统,ping 将脚本暂停 2-3 秒,此时应用程序已退出Application.Exit(),然后 ping 后的下一个命令再次启动它。
Note: The \"puts quotes around the path, incase it has spaces, which cmd can't process without quotes.
注意:\"在路径周围加上引号,以防它有空格,如果没有引号,cmd 无法处理。
Hope this helps!
希望这可以帮助!
回答by Christoph Fink
Why not just the following?
为什么不只是以下?
Process.Start(Application.ExecutablePath);
Application.Exit();
If you want to be sure the app does not run twice either use Environment.Exit(-1)which kills the process instantaneously (not really the nice way) or something like starting a second app, which checks for the process of the main app and starts it again as soon as the process is gone.
如果您想确保应用程序不会运行两次,请使用Environment.Exit(-1)它立即终止进程(不是真正的好方法)或诸如启动第二个应用程序之类的东西,它会检查主应用程序的进程并尽快再次启动它过程没了。
回答by Avner Shahar-Kashtan
Winforms has the Application.Restart()method, which does just that. If you're using WPF, you can simply add a reference to System.Windows.Formsand call it.
Winforms 有Application.Restart()方法,它就是这样做的。如果您使用的是 WPF,则只需添加System.Windows.Forms对它的引用并调用它即可。
回答by Mentezza
You have the initial application A, you want to restart. So, When you want to kill A, a little application B is started, B kill A, then B start A, and kill B.
您有初始应用程序 A,要重新启动。所以,当你想杀死 A 时,会启动一个小应用程序 B,B 杀死 A,然后 B 启动 A,然后杀死 B。
To start a process:
要启动一个过程:
Process.Start("A.exe");
To kill a process, is something like this
杀死一个进程,是这样的
Process[] procs = Process.GetProcessesByName("B");
foreach (Process proc in procs)
proc.Kill();
回答by JeremyK
A lot of people are suggesting to use Application.Restart. In reality, this function rarely performs as expected. I have never had it shut down the application I am calling it from. I have always had to close the application through other methods such as closing the main form.
很多人建议使用Application.Restart。实际上,此功能很少按预期执行。我从未让它关闭我从中调用它的应用程序。我总是不得不通过其他方法关闭应用程序,例如关闭主窗体。
You have two ways of handling this. You either have an external program that closes the calling process and starts a new one,
您有两种处理方法。你要么有一个关闭调用进程并启动一个新进程的外部程序,
or,
或者,
you have the start of your new software kill other instances of same application if an argument is passed as 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
{
}
}
回答by dodgy_coder
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"):
示例 Windows 批处理文件(“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();
回答by Martin.Martinsson
My solution:
我的解决方案:
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;
}
}
}
回答by Pal
For .Net application solution looks like this:
对于 .Net 应用程序解决方案如下所示:
System.Web.HttpRuntime.UnloadAppDomain()
I used this to restart my web application after changing AppSettings in myconfig file.
在 myconfig 文件中更改 AppSettings 后,我用它来重新启动我的 Web 应用程序。
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
configuration.AppSettings.Settings["SiteMode"].Value = model.SiteMode.ToString();
configuration.Save();

