Backing up and restoring power plan with C#

188 Views Asked by At

I making a program that messes around with the Windows power plan. Before making any changes it would be wise to make a copy of the current power plan, so the user can restore it. There is a command prompt command powercfg –restoredefaultschemes but it restores all plans and the user might have some settings that he set manually and I don't want him to lose it. So the only option is to export and then import.

So, as soon as the program starts, I use this code to create a backup of the current scheme if it does not exist:

if (!File.Exists(@".\\PowerPlan.pow"))   
        {
            var cmd = new Process { StartInfo = { FileName = "powercfg" } };
            using (cmd)
            {
                cmd.StartInfo.CreateNoWindow = true;
                cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                cmd.StartInfo.Arguments = $"/export PowerPlan.pow SCHEME_CURRENT"; //saves to the current folder, provide path if needed.
                cmd.Start();
                MessageBox.Show("Profile saved");
            }
        }

In this case, we can use SCHEME_CURRENTto refer to the scheme that we need to export, without even using GUID.

Importing the profile back is easy as well with

cmd.StartInfo.Arguments = $"/-import PowerPlan.pow";
cmd.Start();

However, to actually restore the backed up power plan we need to not just import, but also set it as active. When we changing something in the current power plan and want to set it as active, we can simply use

cmd.StartInfo.Arguments = $"/setactive SCHEME_CURRENT";
cmd.Start();

But when the power plan that we backed up just was imported, we can't use SCHEME_CURRENT(since the current is a modified one), and we don't know the GUID of the imported plan to reference it and set it as active.

Is anybody has an idea of how it can be implemented without knowing GUID? Also, if someone sees a better way to backup/restore power plans I would be glad to hear your ideas and will be very thankful.

0

There are 0 best solutions below