今天简单实现了一下枚举FTP目录的功能,不过有个前提是FTP服务器对我们即将使用的帐号开放LIST权限,不然我们没有权限访问。代码如下:
/*
@param1:strHostName:FTP服务器IP或域名
@param2:nPort:FTP端口号
@param3:strUser:FTP用户名
@param4:strPwd:FTP密码
@param5:strDir:要访问的FTP目录,默认为根目录,可以用FtpSetCurrentDirectory改变
*/
BOOL EnumFtp(CString strHostName,int nPort,CString strUser,CString strPwd,CString strDir="\\")
{
HINTERNET hSession = NULL;
HINTERNET hConnection = NULL;
try
{
hSession = InternetOpen(NULL,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
if (!hSession)
throw "error";
hConnection = InternetConnect(hSession,strHostName,nPort,strUser,strPwd,INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
if (!hConnection)
throw "error";
FtpSetCurrentDirectory(hConnection,strDir);
WIN32_FIND_DATA wfd;
HINTERNET hFind = FtpFindFirstFile(hConnection,_T("*.*"),&wfd,INTERNET_FLAG_DONT_CACHE,NULL);
if (hFind != NULL)
{
do
{
if (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
std::cout<<"文件名:"<<wfd.cFileName<<std::endl;
}
else
{
std::cout<<"目录名:"<<wfd.cFileName<<std::endl;
}
} while (InternetFindNextFile(hFind,&wfd));
InternetCloseHandle(hFind);
}
if (hConnection != NULL)
InternetCloseHandle(hConnection);
if (hSession != NULL)
InternetCloseHandle(hSession);
return TRUE;
}
catch(...)
{
if (hConnection != NULL)
InternetCloseHandle(hConnection);
if (hSession != NULL)
InternetCloseHandle(hSession);
return FALSE;
}
}