1. 程式人生 > >程序自我重啟 --- 實用方法

程序自我重啟 --- 實用方法

重啟 更新 自我重啟 重啟自身 自重啟

1.問題或需求描述:
程序自我重啟,或在局域網環境下更新重啟。

2.解決方法或原理:
可創建前臺或後臺 cmd進程,實現程序更新重啟。

C#代碼:

...
using System.Diagnostics;
using System.IO;
...

private void Restart()
{
        //獲得當前程序信息
        Process cur = Process.GetCurrentProcess();
        FileInfo fi = new FileInfo(cur.MainModule.FileName);

        try
        {
            Process subPro = new Process();
            subPro.StartInfo.UseShellExecute = true;
            subPro.StartInfo.FileName = "cmd";
            subPro.StartInfo.Arguments = " /q /c echo 請勿中斷,正在重啟程序... & ping -n 3 127.1 1>nul 2>nul & taskkill /pid "
                + cur.Id + " 1>nul 2>nul & start \"\" /max \"" 
                + cur.MainModule.FileName + "\"";
            subPro.StartInfo.CreateNoWindow = false;
            subPro.Start();
        }
        catch
        {
                //Add your code
        }
        finally
        {
            Close();
        }
}

private void Update()
{
    try
    {
        //網絡程序位置定義
        const string sNetExePath = @"\\192.168.158.25\setup\Test\test.exe";

        //獲得當前程序信息
        Process cur = Process.GetCurrentProcess();
        FileInfo fi = new FileInfo(cur.MainModule.FileName);

        //獲得網絡位置程序信息
        FileInfo fi2 = new FileInfo(sNetExePath);

        //比較文件修改時間戳,如果網絡文件較新則更新本地程序並重啟
        if (DateTime.Compare(fi2.LastWriteTime, fi.LastWriteTime) > 0)
        {
            try
            {
                Process subPro = new Process();
                subPro.StartInfo.UseShellExecute = true;
                subPro.StartInfo.FileName = "cmd";
                subPro.StartInfo.Arguments = " /q /c echo 請勿中斷,正在更新程序... & ping -n 3 127.1 1>nul 2>nul & taskkill /pid " 
                    + cur.Id + " 1>nul 2>nul & copy /y \"" 
                    + sNetExePath + "\" \"" 
                    + cur.MainModule.FileName 
                    + "\" 1>nul 2>nul && start \"\" /max \"" 
                    + cur.MainModule.FileName + "\"";
                subPro.StartInfo.CreateNoWindow = false;
                subPro.Start();
            }
            catch
            {

            }
            finally
            {
                Close();
            }
        }
    }
    catch
    {

    }
}

程序自我重啟 --- 實用方法