How to download a file with Puppeteer Sharp?

1.9k Views Asked by At

Here is the code that works but it doesn't wait until the completion. How do I make sure the file has been saved?

    var browser = await Puppeteer.LaunchAsync(new LaunchOptions
    {
        ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
        Headless = false,
    });
    var page = (await browser.PagesAsync()).First();
    page.Response += async (object sender, ResponseCreatedEventArgs e) =>
    {
        if (e.Response.Url.Contains(".mp4"))
        {
            byte[] buff = await e.Response.BufferAsync();
            File.WriteAllBytes($"{DateTime.UtcNow.ToFileTime()}.mp4", buff);
        }
    };
    await page.GoToAsync("https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4");
    await Task.Delay(30000);
1

There are 1 best solutions below

0
On

Here, just wrote it:

public static async Task<FileInfo> DownloadFileAsync(string url)
{
    try
    {
        await _page.GoToAsync(url);
    }
    catch (NavigationException)
    {
        // Trying to open a file page throws navigation exception, should be ignored
    }

    await _page.WaitForNetworkIdleAsync();

    while (Directory.GetFiles(_downloadDirectory, "*.crdownload", SearchOption.AllDirectories).Length > 0)
    {
        await Task.Delay(250);
    }

    for (int i = 0; i < 100; i++)
    {
        var finishedFiles = (new DirectoryInfo(_downloadDirectory)).GetFiles();
        var downloadedFile = finishedFiles.OrderByDescending(f => f.LastWriteTime).FirstOrDefault();
        if (downloadedFile != null)
        {
            return downloadedFile!;
        }

        await Task.Delay(250);
    }

    throw new Exception($"Download failed for: {url}");
}