Download file with CefSharp WinForms

crasholino picture crasholino · Dec 15, 2015 · Viewed 19.6k times · Source

I'm trying to download some file (image, audio file, or something else) from my app using CefSharp WinForms. I read many other posts, but nothing seems to work. Do you have any sample code that implements the downloader for CefSharp?

I tried downloading some files, nothing happens.

Answer

crasholino picture crasholino · Dec 16, 2015

After 2 days, finally I did it. For the people who have the same problem, here is the simple solution. If, you are using MinimalExample, you have to download Cefsharp example (cefsharp-master) unzip it and do this:

  1. Right click on your project -> Add exisisting item
  2. Navigate in cefsharp-master -> CefSharp.example -> Select DownloadHandler.cs
  3. Go in your BrowserForm.cs class and type this:

    browser.DownloadHandler = new DownloadHandler();

  4. Done!



DownloadHandler.cs

// Copyright © 2013 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;

namespace CefSharp.Example.Handlers
{
    public class DownloadHandler : IDownloadHandler
    {
        public event EventHandler<DownloadItem> OnBeforeDownloadFired;

        public event EventHandler<DownloadItem> OnDownloadUpdatedFired;

        public void OnBeforeDownload(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
        {
            OnBeforeDownloadFired?.Invoke(this, downloadItem);

            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    callback.Continue(downloadItem.SuggestedFileName, showDialog: true);
                }
            }
        }

        public void OnDownloadUpdated(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
        {
            OnDownloadUpdatedFired?.Invoke(this, downloadItem);
        }
    }
}