c++msdnurlmon

UrlToDownloadFile function not downloading


I am using UrlToDownloadFile function, but it doesn't download the file. No error shown in compiler (using VStudio 2012)

Here is the code:

#include <Windows.h>
#include "urlmon.h"

#pragma lib "urlmon.lib"

using namespace std;

void dwFile();


int _tmain(int argc, _TCHAR* argv[])
{
    dwFile ();
    return 0;
}

void dwFile () 
{
    LPCSTR url = ("http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf");
    LPCSTR fPath = ("C:\\Users\\Andyy\\Desktop\\test\\n3337.pdf");

    HRESULT URLDownloadToFile ((NULL, url, fPath, 0, NULL));
}

Solution

  • Your code is not doing any error handling, and your string handling is wrong. Use this instead:

    #include <Windows.h>
    #include "urlmon.h"
    
    #pragma lib "urlmon.lib"
    
    using namespace std;
    
    void dwFile();
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        dwFile ();
        return 0;
    }
    
    void dwFile () 
    {
        LPCTSTR url = TEXT("http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf");
        LPCTSTR fPath = TEXT("C:\\Users\\Andyy\\Desktop\\test\\n3337.pdf");
    
        HRESULT hr = URLDownloadToFile (NULL, url, fPath, 0, NULL);
        if (FAILED(hr))
        {
            // do something ...
        }
    
        /* or more preffered:
    
        LPCWSTR url = L"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf";
        LPCWSTR fPath = L"C:\\Users\\Andyy\\Desktop\\test\\n3337.pdf");
    
        HRESULT hr = URLDownloadToFileW (NULL, url, fPath, 0, NULL);
        if (FAILED(hr))
        {
            // do something ...
        }
        */
    }
    

    Do note the following comment in the documentation:

    URLDownloadToFile returns S_OK even if the file cannot be created and the download is canceled. If the szFileName parameter contains a file path, ensure that the destination directory exists before calling URLDownloadToFile. For best control over the download and its progress, an IBindStatusCallback interface is recommended.