Introduction
I needed a simple function that downloads files from the
internet (FTP or HTTP). I searched in codeproject and there was nothing useful
for what I wanted. Then I searched codeguru and stumbled on a very simple
function that did more or less what I wanted. I had to modify it, a lot
actually, but it gave me a starting point. Since I needed to download files
from an ftp site I made the function ftp specific. This will work for ftp sites
that allow anonymous login, but it should be easy enough to add the user name
and password to the function parameters to allow access to restricted FTP
sites. Andon M. Coleman wrote the original function. You can find it at the
codeguru site, at http://www.codeguru.com/internet/FileUpload.shtml
The Function
This function uses the Wininet interface classes:
CinternetSession
,
CftpConnection
, and
CftpFileFind
. You pass in the FTP server
(e.g ftp.microsoft.com), the file name on the server with the path name (e.g
“/pub/file.pdf”) and the name you want to save it as (eg. "c:\downloads\file.pdf".
You don’t have to be logged on to the internet while you running this code, but
you should have proxy authentication if you are connected through a proxy
server. This builds with VC++ 6.0, however if you need to include the wininet
classes there in "afxinet.h"
CString CMyApp::GetFTPFile(const char *ftpserver, const char *remotefile,
const char *localfile )
{
TCHAR szCause[255];
CString sCause;
sCause.Format("");
try
{
CInternetSession mysession;
CFtpConnection* pFtpConn = mysession.GetFtpConnection(ftpserver);
if(pFtpConn)
{
CFtpFileFind finder(pFtpConn);
BOOL bWorking = finder.FindFile(remotefile);
if(bWorking)
{
BOOL bGot = pFtpConn->GetFile(remotefile,localfile);
}
else
{
sCause.Format("The File specified could not be found. "
"Check your spelling and try again!!");
}
}
else
{
sCause.Format("Could not connect to ftp server!! \nPlease "
"ensure you have correct address and access rights!");
}
}
catch(CException* error)
{
error->GetErrorMessage(szCause,254,NULL);
sCause.Format("%s",szCause);
}
return (sCause);
}
All you have to do is to copy the function and integrate it with your application, since there isn't much code involved i din't see the point in creating a project for this or even a class! I have made the return value a
CString
to get the error as well as well as a return value.
Usage
The return value indicates success if the return string is empty, otherwise you'll get the error.
..
..
CString sRet= GetFTPFile("ftp.microsoft.com","/pub/subfolder/file.pdf","file.pdf");
if(!sRet.IsEmpty())
AfxMessageBox(sRet);
..
Finally
As I said this is supposed to be very simple function for beginners or for someone who just wants a quick solution. Feel free to comment, modify this code and let me know if you have a better idea.
Cheers!
Ali
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.