Use HttpClient in DownloadFileAsync function

This commit is contained in:
Jaex 2023-10-27 10:19:36 +03:00
parent d32a050db7
commit 1c29fbe022
3 changed files with 36 additions and 31 deletions

View file

@ -618,24 +618,26 @@ public static string GetFileNameFromWebServer(string url)
return fileName;
}
public static void DownloadFile(string url, string filePath)
public static async Task DownloadFileAsync(string url, string filePath)
{
if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(filePath))
{
FileHelpers.CreateDirectoryFromFilePath(filePath);
using (WebClient wc = new WebClient())
{
wc.Headers.Add(HttpRequestHeader.UserAgent, ShareXResources.UserAgent);
wc.Proxy = HelpersOptions.CurrentProxy.GetWebProxy();
wc.DownloadFile(url, filePath);
}
}
}
HttpClient client = HttpClientFactory.Create();
public static async Task DownloadFileAsync(string url, string filePath)
using (HttpResponseMessage responseMessage = await client.GetAsync(url))
{
await Task.Run(() => DownloadFile(url, filePath));
if (responseMessage.IsSuccessStatusCode)
{
using (Stream stream = await responseMessage.Content.ReadAsStreamAsync())
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
await stream.CopyToAsync(fileStream);
}
}
}
}
}
public static async Task<string> DownloadStringAsync(string url)
@ -662,6 +664,8 @@ public static async Task<Bitmap> DownloadImageAsync(string url)
{
Bitmap bmp = null;
if (!string.IsNullOrEmpty(url))
{
HttpClient client = HttpClientFactory.Create();
using (HttpResponseMessage responseMessage = await client.GetAsync(url))
@ -682,15 +686,16 @@ public static async Task<Bitmap> DownloadImageAsync(string url)
if (supportedImageTypes.Contains(mediaType, StringComparer.OrdinalIgnoreCase))
{
byte[] data = await responseMessage.Content.ReadAsByteArrayAsync();
MemoryStream ms = new MemoryStream(data);
MemoryStream memoryStream = new MemoryStream(data);
try
{
bmp = new Bitmap(ms);
bmp = new Bitmap(memoryStream);
}
catch
{
ms.Dispose();
memoryStream.Dispose();
}
}
}
}

View file

@ -425,7 +425,7 @@ private static void DownloadFFmpeg()
string filePath = Path.Combine(OutputDir, fileName);
Console.WriteLine("Downloading: " + FFmpegDownloadURL);
URLHelpers.DownloadFile(FFmpegDownloadURL, filePath);
URLHelpers.DownloadFileAsync(FFmpegDownloadURL, filePath).GetAwaiter().GetResult();
Console.WriteLine("Extracting: " + filePath);
ZipManager.Extract(filePath, OutputDir, false, entry => entry.Name.Equals("ffmpeg.exe", StringComparison.OrdinalIgnoreCase));

View file

@ -1092,7 +1092,7 @@ private bool DownloadFromURL(bool upload)
try
{
URLHelpers.DownloadFile(url, Info.FilePath);
URLHelpers.DownloadFileAsync(url, Info.FilePath).GetAwaiter().GetResult();
if (upload)
{