Search code examples
c#windowsapiconsolewindows-update

Reboot when required - c# and Windows Update


I'm building a c# console application that automatically finds updates, downloads them and installs them.

I'm using this method for the installation part:

        public static void InstallUpdates(UpdateCollection DownloadedUpdates)
    {
        UpdateSession UpdateSession = new UpdateSession();
        UpdateInstaller InstallAgent = UpdateSession.CreateUpdateInstaller() as UpdateInstaller;
        InstallAgent.Updates = DownloadedUpdates;

        //Starts a synchronous installation of the updates.
        // http://msdn.microsoft.com/en-us/library/windows/desktop/aa386491(v=VS.85).aspx#methods
        IInstallationResult InstallResult = InstallAgent.Install();

    }

According to this link, I can check whether or not a reboot is required. What I want to achieve is a system reboot that is done immediately when the RebootRequiredBeforeInstallation changes to true.

I thought of doing this, but that won't work because I can't use an else statement:

        while (!InstallAgent.RebootRequiredBeforeInstallation)
        {

        } else
        {
            // Reboot
        }

What would be the correct approach to this?


Solution

  • How about this:

    while (!InstallAgent.RebootRequiredBeforeInstallation)
    {
        // Install things
        // If the installer sets the RebootRequiredBeforeInstallation flag to
        // true, the while loop will terminate and you can reboot.
    }
    
    if (InstallAgent.RebootRequiredBeforeInstallation)
    {
        // Reboot
    }