How do I get the correct case of a path?
I have a small but itching problem. How do I get the correct case for a Windows path in Qt?
Let's say i have a pa开发者_C百科th c:\documents and settings\wolfgang\documents
stored in a QString str
and i want to know the correct case, here C:\Document and Settings\Wolfgang\Documents
. QDir(str).absolutePath()
doesn't get me the path with correct case.
Any suggestions, since I have no clue what else i could try?
Thank you for your time!
There isn't a simple way to do this, but you can try doing a QDir.entryList, and then do a case insensitive search on the results. This will provide you with the correct filename. You'll then need to get the absolutePath
for that result.
This should give you the preserved-case for the path/filename.
I think the solution currently accepted by the OP, with listing all children items on each directory level of the path, is really inefficient, quick and dirty. There must be a better way. Because this problem with case-correct path relates only to Windows (other platforms are case-sensitive, AFAIK), I think it is perfectly correct to use #ifdef
and call to Windows API and write something like this:
#if defined(Q_OS_WIN32)
#include <Windows.h>
// Returns case-correct absolute path. The path must exist.
// If it does not exist, returns empty string.
QString getCaseCorrectPath(QString path)
{
if (path.isEmpty())
return QString();
// clean-up the path
path = QFileInfo(path).canonicalFilePath();
// get individual parts of the path
QStringList parts = path.split('/');
if (parts.isEmpty())
return QString();
// we start with the drive path
QString correctPath = parts.takeFirst().toUpper() + '\\';
// now we incrementally add parts one by one
for (const QString &part : qAsConst(parts))
{
QString tempPath = correctPath + '\\' + part;
WIN32_FIND_DATA data = {};
HANDLE sh = FindFirstFile(LPCWSTR(tempPath.utf16()), &data);
if (sh == INVALID_HANDLE_VALUE)
return QString();
FindClose(sh);
// add the correct name
correctPath += QString::fromWCharArray(data.cFileName);
}
return correctPath;
}
#endif
I have not tested it, there might be some minor issues. Please let me know if it does not work.
You can use QFileInfo
for that and the function
QString QFileInfo::absoluteFilePath () const
will return the absolute file path.
E.g:
QFileInfo yourFileInfo(yourPath);
QString correctedCasePath = yourFileInfo.absoluteFilePath ();
Another advantage is that, yourPath
can be a QFile
or QString
so that you can use it directly with the handle currently you are having. Besides these, there are other operations are also available through QFileInfo
that can obtain useful information about the file being referred to..
Hope it helps..
精彩评论