InternetOpenUrl如何检测文件是否不存在 [英] InternetOpenUrl How to Detect if file dont exist

查看:80
本文介绍了InternetOpenUrl如何检测文件是否不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好.我正在使用InternetOpen InternetOpenUrl从服务器下载一些文件....
我的问题是,当远程服务器不存在文件时,它将使用给定名称创建文件,文件大小为1kb,并且dosnt返回false.
如何检测远程文件是否存在,如果不存在,则返回false;
这是我用来从互联网获取文件的代码:

Hello. I am using InternetOpen InternetOpenUrl to download some files from my server....
My problem is when a file is not exist to the remote server it creates a file with the given name with 1kb size and dosnt return false .
How can i detect if the remote file exists and if not exists return false;
This is my code using to get files from internet:

bool HTTPGetFile(const CString fileURL,const CString fileName, bool sh_progress)
{
	// Open the internet session
	HINTERNET hInet = InternetOpen(AfxGetAppName(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(hInet == NULL)
		return false;

	HINTERNET hFile;
	// Open the required URL
	try
	{
		hFile = InternetOpenUrl(hInet, fileURL, NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0);

	}
	catch (CInternetException *pEx)
	{
		pEx->Delete();
		return false;
	}
	if(hFile == NULL)
		return false;

	DeleteUrlCacheEntry(fileURL);
	TCHAR dwByteToRead[32];
	DWORD dwSizeOfRq = 32;
	DWORD dwFileSize = 0;
	DWORD dwInfoSize = 0;
	BOOL bGotFileSize = FALSE;

	if(HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH, dwByteToRead, &dwSizeOfRq , NULL))
	{
		bGotFileSize = TRUE;
		dwFileSize = (DWORD) _ttol(dwByteToRead);
	}

	CFile m_FileToWrite;
	if(!m_FileToWrite.Open(fileName, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite))
	{
		return false;
	}
	char szReadBuf[1024];
	DWORD dwBytesToRead = 1024;
	DWORD dwBytesRead = 0;
	DWORD dwTotalBytesRead = 0;
	do 
	{
		if(!InternetReadFile(hFile, szReadBuf, dwBytesToRead, &dwBytesRead))
		{
			InternetCloseHandle(hFile);
			InternetCloseHandle(hInet);
			m_FileToWrite.Close();
			return false;
		}
		if (!dwBytesRead)// Transfer is complete.
			break;
		else
		{
			m_FileToWrite.Write(szReadBuf, dwBytesRead);
			if(sh_progress && bGotFileSize)
			{
				dwTotalBytesRead += dwBytesRead;
				m_fileProgBar.SetPos(100 * dwTotalBytesRead/dwFileSize);
			}
		}
	} while (TRUE);

	InternetCloseHandle(hFile);
	InternetCloseHandle(hInet);
	m_FileToWrite.Close();
	m_fileProgBar.SetPos(0);
	return true;
} 

推荐答案

下面的链接显示了delphi代码,但想法是相同的.您可以创建相同的机制来检查文件是否存在.
http://www.cryer.co.uk/brian/delphi/wininet/example_isurlvalid.htm [^ ]

祝你好运!
The following link shows delphi code but the idea is the same. You can create the same mechanism for checking if the file exists or not.
http://www.cryer.co.uk/brian/delphi/wininet/example_isurlvalid.htm[^]

Good luck!


这篇关于InternetOpenUrl如何检测文件是否不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆