c++winapiurlmon

Download to current directory


I want to download the file to current directory instead of "c://". How would that be done?

My code:

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

Solution

  • The reference for URLDownloadToFile() says this about the szFileName parameter (emphasis mine):

    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.

    If you pass only a file name instead of a full path, it will download to the current directory. This is not explicitly documented but it is the normal way how the Windows API works.

    Though I wouldn't take any chances that the current directory at the time of the call to URLDownloadToFile() is the same as it was at the start of the program. Any code may have called SetCurrentDirectory() to change the current directory to something else.

    To make the code more robust I would call GetCurrentDirectory() only once at the start of the program and store the path in a variable. Before calling URLDownloadToFile() I would append the filename to that path and pass the full path for the szFileName parameter.

    On a side note, you should call CoInitialize() at the start and CoUninitialize() at the end of a program that uses URLDownloadToFile() because it is a COM API. You might get away without that but that would be pure luck and may cease to work in different Windows versions.