所以目前我正在嘗試從瀏覽器下載檔案;
Process.Start("explorer.exe", "link");
由于它是一個cdn.discordapp鏈接,它會立即下載檔案。以下代碼在下載檔案夾和桌面中搜索下載檔案。
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");
其余代碼匯入powerplan通過cmd并將其設定powerplan為活動。
//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();
問題:
- 要下載檔案,必須打開任何瀏覽器。
- 下載有效,但瀏覽器不會自動關閉。
- 用戶下載路徑未知。
我想在不讓應用程式失去焦點的情況下下載檔案。我還希望瀏覽器在下載完成后自動關閉。
uj5u.com熱心網友回復:
我建議不要使用Process.Start命令來啟動瀏覽器,而是在您的 C# 代碼中創建一個 HttpClient,它將為您下載檔案并將其保存在本地。這使您可以最終控制檔案。下載檔案后,您可以呼叫您Process.Start的檔案并對下載的檔案執行任何您需要的操作。
有多個如何使用 C# 下載檔案的示例,但這里有一個快速要點:
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
}
uj5u.com熱心網友回復:
這對我有用。
using (WebClient wc = new WebClient())
{
wc.DownloadFileAsync(
// Link
new System.Uri("https://cdn.discordapp.com/attachments/link.pow"),
// Path to save
"C:\\link.pow"
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/481531.html
