0

我正在使用 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));
}
4

1 回答 1

1

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

#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 也会返回 S_OK 。如果 szFileName 参数中包含文件路径,请在调用 URLDownloadToFile 之前确保目标目录存在。为了更好地控制下载及其进度,建议使用 IBindStatusCallback 接口

于 2016-01-21T08:13:48.367 回答