Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Download Large File Efficiently

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading