I have written following method to download file and save in c# with .net framework 4.7.2 is being used.
public static bool DownloadFiles(Uri url, string filePath)
{
try
{
using (HttpClient client = new HttpClient())
{
using (var stream = client.GetStreamAsync(url))
{
using (var fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
stream.Result.CopyTo(fs);
}
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
Is above code is efficient for large file, I tried to do some performance analysis but haven’t drawn some definite conclusion. I am new to C# as it is not my primary tech stack, Any suggestion will be hugely helpful.
>Solution :
This function should be async. HttpClient should be NOT disposed Call a Web API From a .NET Client (C#):
public static class HttpUtils
{
static HttpClient client = new HttpClient();
public static async Task<bool> DownloadFilesAsync(Uri url, string filePath)
{
try
{
using (var stream = await client.GetStreamAsync(url))
{
using (var fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
await stream.CopyToAsync(fs);
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
}