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.
CodePudding user response:
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
}
CodePudding user response:
This worked for me.
using (WebClient wc = new WebClient())
{
wc.DownloadFileAsync(
// Link
new System.Uri("https://cdn.discordapp.com/attachments/link.pow"),
// Path to save
"C:\\link.pow"
);