我是C ++的新手,并尝试编写一个更新函数。

使用URLDownloadToFile进行的下载可以正常进行,但是如果我将URL更改为无效的URL,它仍然返回S_OK ...如何检查下载是否成功?

#include <WinInet.h>
#include <iomanip>

int download_file (const TCHAR urldownload[],const TCHAR target[] )
{
    DownloadProgress progress;
    IBindStatusCallback* callback = (IBindStatusCallback*)&progress;

    SCP(40, NULL); cout << target;

    HRESULT status = URLDownloadToFile(NULL, urldownload, target, 0, static_cast<IBindStatusCallback*>(&progress));
    Sleep(200);
    DeleteUrlCacheEntry(urldownload);

    wcout << status;

    if (status == S_OK) cout << "yes";
    else(cout << "Download failed");

    Sleep(10000); return 1;
}


class DownloadProgress : public IBindStatusCallback {
public:
HRESULT __stdcall QueryInterface(const IID &, void **) {
    return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef(void) {
    return 1;
}
ULONG STDMETHODCALLTYPE Release(void) {
    return 1;
}
HRESULT STDMETHODCALLTYPE OnStartBinding(DWORD dwReserved, IBinding *pib) {
    return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetPriority(LONG *pnPriority) {
    return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnLowResource(DWORD reserved) {
    return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE OnStopBinding(HRESULT hresult, LPCWSTR szError) {
    return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetBindInfo(DWORD *grfBINDF, BINDINFO *pbindinfo) {
    return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC *pformatetc, STGMEDIUM *pstgmed) {
    return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(REFIID riid, IUnknown *punk) {
    return E_NOTIMPL;
}

virtual HRESULT __stdcall OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText)
{
    //wcout << ulProgress << L" of " << ulProgressMax << endl; Sleep(200);
    if (ulProgress != 0 && ulProgressMax != 0)
    {
        double output = (double(ulProgress) / ulProgressMax)*100;
        cout << "\r" << "Downloading: " << fixed << setprecision(2) << output << " %  " ; Sleep(20);
    }
    return S_OK;
}
};

最佳答案

MSDN article has the answer为您:


  即使无法创建文件并且取消下载,URLDownloadToFile也会返回S_OK。如果szFileName参数包含文件路径,请在调用URLDownloadToFile之前确保目标目录存在。为了最好地控制下载及其进度,建议使用IBindStatusCallback界面。


您需要提供状态回调以接收异步操作的状态。您的代码段已经有了基础。 OnProgressOnStopBinding应该会为您提供下载失败的结果。

09-30 12:48