下载到当前目录

Download to current directory

我想将文件下载到当前目录而不是 "c://"。怎么做到的?

我的代码:

using namespace std;
#pragma comment(lib, "urlmon.lib")

int main()
{
    cout << "downloading update";
    HRESULT hr = URLDownloadToFile(NULL, _T("http://download.piriform.com/ccsetup233.exe"), _T("c://ccsetup233.exe"), 0, NULL);
    FreeConsole();
}

URLDownloadToFile() 的参考文献对 szFileName 参数(强调我的)说了这个:

A pointer to a string value containing the name or full path of the file to create for the download. If szFileName includes a path, the target directory must already exist.

如果您只传递文件名而不是完整路径,它将下载到当前目录。这没有明确记录,但这是 Windows API 工作的正常方式。

虽然我不会冒险调用 URLDownloadToFile() 时的当前目录与程序开始时的目录相同。任何代码都可能调用 SetCurrentDirectory() 将当前目录更改为其他目录。

为了使代码更健壮,我会在程序开始时只调用一次 GetCurrentDirectory() 并将路径存储在变量中。在调用 URLDownloadToFile() 之前,我会将文件名附加到该路径并传递 szFileName 参数的完整路径。

附带说明一下,您应该在使用 URLDownloadToFile() 的程序开始时调用 CoInitialize() 并在结束时调用 CoUninitialize(),因为它是一个 COM API .没有它你可能会逃脱,但这纯粹是运气,并且可能会停止在不同的 Windows 版本中工作。