'Downloading and selecting a powercfg file to import it with c# and not losing focus on the application after the download

So currently I'm trying to download a file form the browser;

Process.Start("explorer.exe", "link");

Since it's a cdn.discordapp link it downloads the file immediately. The following code searches for the download file in the download folder and the desktop.

var cmdA = new Process { StartInfo = { FileName = "powercfg" } };
    using (cmdA) //This is here because Process implements IDisposable
    {

        var inputPathA = Path.Combine(Environment.CurrentDirectory, "C:\\Users\\god\\Desktop\\1.pow");

The rest of the code imports the powerplan via cmd and sets the powerplan as active.

//This hides the resulting popup window
cmdA.StartInfo.CreateNoWindow = true;
cmdA.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

//Prepare a guid for this new import
var guidStringA = Guid.NewGuid().ToString("d"); //Guid without braces

//Import the new power plan
cmdA.StartInfo.Arguments = $"-import \"{inputPathA}\" {guidStringA}";
cmdA.Start();

//Set the new power plan as active
cmdA.StartInfo.Arguments = $"/setactive {guidStringA}";
cmdA.Start();

Issues:

  • To download the file, any browser has to be opened.
  • The download works but the browser does not close automatically.
  • Users download path is unknown.

I want to download the file without having the application lose focus. I also want the browser to close automatically after the download is complete.



Solution 1:[1]

I would suggest not using a Process.Start command to fire up a browser, but instead create an HttpClient in your C# code that will download your file for you and save it locally. This gives you ultimate control over the file. Once the file has downloaded, you can invoke your Process.Start and do whatever you need to with the downloaded file.

There are multiple examples of how to download a file using C#, but here's a quick gist:

async Task DownloadFile(string url, string localFileName)
{
    using (var client = new HttpClient())
    using (var response = await client.GetAsync(url))
    using (var fs = new FileStream(localFileName, FileMode.CreateNew))
    {
        await response.Content.CopyToAsync(fs);
    }

    // Do something with the file you just downloaded
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthew M.