Search code examples
c#windowspowercfg

How to import a Windows Power Plan with C#


I'm working on a small C# app that will import a power plan to the user's PC and set it as active. It working perfectly with a .bat file when the .pow file is in the same folder and I'm running commands:

powercfg -import "%~dp0\Optimized.pow"
powercfg /setactive 62ffd265-db94-4d48-bb7a-183c87641f85

Now, in C# I tried this:

  Process cmd = new Process();
  cmd.StartInfo.FileName = "powercfg";
  cmd.StartInfo.Arguments = "-import \"%~dp0\\Optimized\"";
  cmd.StartInfo.Arguments = "powercfg /setactive 62ffd265-db94-4d48-bb7a-183c87641f85";
  cmd.Start(); 

  //and this:
  private void button1_Click(object sender, EventArgs e)
  {
      Process cmd = new Process();
      cmd.StartInfo.FileName = "cmd.exe";
      cmd.StartInfo.RedirectStandardInput = true;
      cmd.StartInfo.RedirectStandardOutput = true;
      cmd.StartInfo.CreateNoWindow = true;
      cmd.StartInfo.UseShellExecute = false;
      cmd.Start();
      cmd.StandardInput.WriteLine("powercfg -import \"%~dp0\\Optimized\"");
      cmd.StandardInput.WriteLine("powercfg /setactive 6aa8c469-317b-45d9-a69c-f24d53e3aff5");
      cmd.StandardInput.Flush();
      cmd.StandardInput.Close();
      cmd.WaitForExit();
      Console.WriteLine(cmd.StandardOutput.ReadToEnd());
  }

But the program doesn't see the .pow file in the project folder (I actually tried to put it in each and every folder in the project). How it can be implemented to let the powercfg see the file?

Any help is much appreciated! Thanks!


Solution

  • You could try something like this:

    var cmd = new Process {StartInfo = {FileName = "powercfg"}};
    using (cmd) //This is here because Process implements IDisposable
    {
    
       var inputPath = Path.Combine(Environment.CurrentDirectory, "Optimized.pow");
    
       //This hides the resulting popup window
       cmd.StartInfo.CreateNoWindow = true;
       cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    
       //Prepare a guid for this new import
       var guidString = Guid.NewGuid().ToString("D"); //Guid without braces
    
       //Import the new power plan
       cmd.StartInfo.Arguments = $"-import \"{inputPath}\" {guidString}";
       cmd.Start();
    
       //Set the new power plan as active
       cmd.StartInfo.Arguments = $"/setactive {guidString}";
       cmd.Start();
    }
    

    This fixes the Arguments parameter that is being overwritten/used twice, as well as correctly disposes of the cmd variable. Additional lines added to hide the resulting pop-up window, and for generating the Guid upfront and specifying it as part of the command line.