用CInternetSession下载文件

bool InternetDownload(const CString &strURL, const CString &strFN)
...{
    
    CInternetSession internetSession("SecurityScan.exe",0);
    //第一个参数不能为空
    
    
    BOOL bSucceed = TRUE;
    
    try
    ...{
        CStdioFile * pFile = internetSession.OpenURL(strURL);
        
        if(pFile != NULL)
        ...{
            
            
            CFile cf;
            if(!cf.Open(strFN, CFile::modeCreate | CFile::modeWrite, NULL))
            ...{
                return FALSE;
            }
            
            BYTE Buffer[512];
            
            ZeroMemory(Buffer, sizeof(Buffer));
            int nReadLen = 0;
            
            while((nReadLen = pFile->Read(Buffer, sizeof(Buffer))) > 0)
            ...{
                cf.Write(Buffer, nReadLen);
            }
            
            cf.Close();
            pFile->Close() ;
            
            delete pFile;
            
        }
    }
    catch (CInternetException& e)
    ...{
        char szBuffer[128];
        ZeroMemory(szBuffer, sizeof(szBuffer));
        e.GetErrorMessage(szBuffer, sizeof(szBuffer), NULL);
        TRACE("InternetDownload, Exception: %s ",szBuffer);
    }
    catch(...)
    ...{
        TRACE("InternetDownload, Exception: ... ");
    }
    internetSession.Close() ;
    
    
    if(!bSucceed)
        DeleteFile(strFN);
    return bSucceed;
}


调用如下:

InternetDownload(strURL, strFN);

strURL为下载地址

strFN为存放路径

 

头文件记得包含afxinet.h

你可能感兴趣的:(用CInternetSession下载文件)