Using FTP from your MFC application - Quick Reference

Introduction

Tutorial for using FTP

Description

	This tutorial helps you to use FTP from your applications. You can 

	a) Connect to a FTP server and 
	b) Upload or Download files from and to the server.

Implementation

Step 1

	Add the following statement in your header file.

	#include < afxinet.h >

Step 2

	In your header file, add the following Member Variables
 
	CFtpConnection *m_pFtpConnection;
	CInternetSession m_Session;

Step 3

	In your application's initialization ( OnInitDialog or InitInstance functions), 
	add the following lines.

	m_pFtpConnection = NULL;

	try
	{
	  // Here usr is the username, pwd is the password and ftpsite.com is the name 
	  // of the ftp site which you want to connect to.
	  m_pFtpConnection = m_Session.GetFtpConnection("ftpSite.com","usr","pwd",
							INTERNET_INVALID_PORT_NUMBER);
	}
	catch(CInternetException *pEx)
	{
		pEx->ReportError(MB_ICONEXCLAMATION);
		m_pFtpConnection = NULL;
		pEx->Delete();
	}
	return TRUE;

Step 4

	To upload a file, add the following lines of code :- 

	CFileFind Finder;
	CString strFileName;

	// Here c:\\Myfile.bmp is the name of the file that you want to upload
	// It neednt necessarily be a bitmap file. You can upload any file that you
	// want to. 
	// The CString strFileName is used so that the same name is uploaded 
	// to the ftp server.
	// After uploading, the file in the ftp server will have the same name as 
	// your local file.You can also rename it to anything else.

	if(Finder.FindFile("C:\\Myfile.bmp")==TRUE)
	{
		Finder.FindNextFile();
		strFileName = Finder.GetFileName();
		Finder.Close();
	}

	BOOL bUploaded = m_pFtpConnection->PutFile("C:\\Myfile.bmp",strFileName,
						    FTP_TRANSFER_TYPE_BINARY,1);

	AfxMessageBox("Uploaded Successfully");

Step 5

	To download a file from a ftp site, you can use the following code. 
	
	Here the first parameter is the file in the ftp server.
	The 2nd parameter is the location where you want to store it in your hard disk.

	m_pFtpConnection->GetFile("File.ext","C:\\File.ext",TRUE,
				   FILE_ATTRIBUTE_NORMAL,FTP_TRANSFER_TYPE_BINARY,1);

Step 6

	To close the connection 
	
	m_Session.Close();
	m_pFtpConnection->Close();

	if(m_pFtpConnection!=NULL)
	  delete m_pFtpConnection;

Conclusion

Thats it folks. Have a great time FTPing... All Luck.
Hosted by www.Geocities.ws

tutorials /
ftp
home /
Hosted by www.Geocities.ws

1