Get finished download in CefSharp

2019-08-02 17:02发布

问题:

I try do make a small downloader-tool for a website with CefSharp. For downloading files, I use the pretty well example DownloadHandler from CefSharp. Now, I want to do some things after the download is finished. I know the "downloadItem" has a "IsComplete" value. But if I put something like this in the "OnDownloadUpdated" method, stuff will never be executed

        if (downloadItem.IsComplete) {
            //do stuff
        }

So, my question is, where I have to check if my downloaded item is completed?

EDIT: Complete DownloadHandler:

    public class DownloadHandler : IDownloadHandler {

    public event EventHandler<DownloadItem> OnBeforeDownloadFired;
    public event EventHandler<DownloadItem> OnDownloadUpdatedFired;
    private bool stop;
    private DownloadWindow window;

    public void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback) {
        var handler = OnBeforeDownloadFired;
        if (handler != null) {
            handler(this, downloadItem);
        }

        if (!callback.IsDisposed) {
            using (callback) {
                callback.Continue(downloadItem.SuggestedFileName, showDialog: true);
            }
        }
        window = new DownloadWindow(downloadItem.TotalBytes, downloadItem.SuggestedFileName, this);
        window.Show();
    }

    public void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback) {
        var handler = OnDownloadUpdatedFired;
        if (handler != null) {
            handler(this, downloadItem);
        }

        if (window != null) {
            window.UpdateProgress(downloadItem.ReceivedBytes);
        }

        if (stop) {
            callback.Cancel();
        }
    }

    public void StopDownload() {
        stop = true;
    }
}

回答1:

You need to check it inside the OnDownloadUpdated method.

public void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
{

    if (downloadItem.IsComplete || downloadItem.IsCancelled)
        {
         //do stuff
        }
}

Don't forget, your class must implement the IDownloadHandler interface. A good debugging strategy would be placing breakpoints inside this method, to see/understand when it gets fired.