ソフトウェアの更新機能の実装

.exe ファイルを置き換える

こちらの記事を参考に実装。update ディレクトリに Update.exe を置くと、それを更新データとして現在の Update.exe と置き換える。

http://mo.kerosoft.com/095

public partial class MainWindow : Window
{
    public MainWindow()
    {
        Clean();
        InitializeComponent();
    }

    private void Clean()
    {
        if (Environment.CommandLine.IndexOf("/up", StringComparison.CurrentCultureIgnoreCase) != -1)
        {
            try
            {
                string[] args = Environment.GetCommandLineArgs();
                int pid = Convert.ToInt32(args[2]);
                Process.GetProcessById(pid).WaitForExit();    // 終了待ち
            }
            catch (Exception)
            {
            }
            File.Delete("Update.old");
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if(File.Exists("update/Update.exe"))
        {
            File.Delete("Update.old");
            File.Move("Update.exe", "Update.old");
            File.Move("update/Update.exe", "Update.exe");
            Process.Start("Update.exe", "/up " + Process.GetCurrentProcess().Id);
            this.Close();
        }
        else
        {
            textBlock.Text = "update not found.";
        }
    }
}