Check if a folder is writable using C++/MFC on Windows



This function checks if a file can be created inside a folder by creating a temporary file inside the folder. Additionally, if the whole path doesn’t exist, then it keeps going up one level until it finds a writable folder. Coded in C++/MFC.

 
//The path accepts even the folder that do not exist
//eg: C:\Program Files\A\B\C
//The function will check if C exists, if not it will check if B
//exist etc etc..until it finds a path that exists
//and then it will try to create a file in that folder
BOOL IsFolderWritable(CString strPath, BOOL bContainsFileName)
{
 
	//we will remove file name
	if (bContainsFileName)
	{
		PathRemoveFileSpec(strPath.GetBufferSetLength(1024));
		strPath.ReleaseBuffer();
	}
 
	while(!PathFileExists(strPath))
	{
		TrimPath(strPath, 1, FALSE);
	}
 
	strPath.Trim();
	if (strPath.IsEmpty()) return FALSE;
 
	//now try to create a temporary file here
	//if it creates successfully then the folder is
	//writeable
 
	CString strTempFilePath;
	UINT nRet = 0;
	nRet = GetTempFileName(strPath, _T("Tmp"), 0, strTempFilePath.GetBufferSetLength(1024));
	strTempFilePath.ReleaseBuffer();
 
	if ( 0 == nRet)
	{
		return FALSE;
	}
 
	DeleteFile(strTempFilePath);
 
	return TRUE;
 
}
 
 
 
void TrimPath(CString &strPathToTrim, int iLevel, BOOL bIncludesFileName)
{
	int iCtr = 0;
 
	// this function uses an easier logic.
	// initially it removes backshash from the end of the path
	// if a file name is at the end of the path then
	// iLevel is incremented by 1
 
	RemoveBackslash(strPathToTrim);
 
	if (bIncludesFileName)
	{
		//this is because we will have to cut the file name also
		iLevel++;
	}
 
	while ( iCtr < iLevel )
	{
		int idx = strPathToTrim.ReverseFind(_T('\\'));
 
		if (idx != 0)
		{
			//without backslash
			strPathToTrim = strPathToTrim.Left(idx);
		}
 
		iCtr++;
	}
 
	//now we will append backslash
	AppendBackslash(strPathToTrim);
 
}
 
//Appends a backslash if it exist
void AppendBackslash( CString & strPath)
{
	if ( !IsBackslashPresent(strPath) )
	{
        strPath += _T('\\');
	}
}
 
void RemoveBackslash( CString & strPath)
{
	int iLength;
 
	if ( IsBackslashPresent(strPath) )
	{
		iLength = strPath.GetLength();
        strPath = strPath.Left(iLength-1);
	}
}
 
BOOL IsBackslashPresent( CString & strPath )
{
	if (strPath.IsEmpty()) return FALSE;
 
	if (strPath.Right(1) == _T('\\')) return TRUE;
 
	return FALSE;
 
}


Leave a Reply

Your email address will not be published. Required fields are marked *