c# cef 判断文件下载是否完成

最近做一个抓取,通过cef post提交参数,返回下载文件,需要判断文件是否下载完成。

解决:重写 IDownloadHandler 接口

using CefSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CefSharpSimpleDemo
{
    class DownloadHandler : IDownloadHandler
    {
        public string GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
        public void OnBeforeDownload( IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
        {
            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    DownCrawler.isDownload = false;   //标识置为false,表示正在下载
                    string fileLocation = downloadItem.SuggestedFileName.Substring(0, downloadItem.SuggestedFileName.IndexOf(".")); //文件路径
                    Debug.WriteLine(fileLocation);
                    callback.Continue(@"C:\Downloads\one\" +GetTimeStamp()+downloadItem.SuggestedFileName,
                        showDialog: false); //设置文件存放路径
                }
            }
        }

        public void OnDownloadUpdated( IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
        {
            //如果下载完成
            if (downloadItem.IsComplete)
            {
                Debug.WriteLine("下载完成");
                DownCrawler.isDownload = true;  //标识置为true,表示下载完成
            }
        }
    }

    public class DownCrawler
    {
        public static bool isDownload;
    }
}

调用

browser.DownloadHandler = new DownloadHandler();

然后在执行代码中 插入循环判断 下载标识 是否为true

while(!DownCrawler.isDownload){
  Thread.Sleep(2000);  
}


发表评论 / Comment

用心评论~