UrlToDownloadFile 函数不下载

UrlToDownloadFile function not downloading

我正在使用 UrlToDownloadFile 函数,但它没有下载文件。编译器中没有显示错误(使用 VStudio 2012)

代码如下:

#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));
}

您的代码没有进行任何错误处理,您的字符串处理有误。改用这个:

#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 ...
    }
    */
}

请注意文档中的以下注释:

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.