Qurl isValid
-
Using the following code,
@
QUrl urlConnection = QUrl::fromUserInput(str);
std::cout << "tostring: " << urlConnection.toString().toStdString() << std::endl;
std::cout << "valid: " << (urlConnection.isValid() ? "true" : "false") << std::endl;
std::cout << "toLocalFile: " << urlConnection.toLocalFile().toStdString() << std::endl;
QDir d(urlConnection.toLocalFile());
std::cout << "file exists: " << (d.exists() ? "true" : "false") << std::endl;
@When str is equal to file:///C:/Temp/Storage the following output is produced;
bq. tostring: file:///C:/Temp/Storage
valid: true
toLocalFile: C:/Temp/Storage
file exists: trueWhen str is equal to file://C:/Temp/Storage (notice only two slashes) the following output is produced;
bq. tostring: file://c/Temp/Storage
valid: true
toLocalFile: //c/Temp/Storage
file exists: falseIn the second example QUrl reports the instance as valid but when using it with QDir::exists it fails. So is the QUrl instance in fact valid in this case? Or am I using the object incorrectly?
-
I don't really understand your question. Why not just use the first one?
If the second one fails? -
The string in question will be specified in a configuration file, so the value can change and I need a way to valid the data.
The idea was to delegate the parsing of the string to QUrl and just check the isValid method prior to using the value. However, if I cannot trust this method to return the correct result then I might need to look elsewhere. Obviously there might be some flaw with my reasoning hence this post.
-
//c/temp is a UNC path (shared folder "temp" on machine name "c")
The specification for file: urls isfile://host/path
If the host is empty, the path is on the local machine (that's why the "file:///" prefix is usual)
All the major browsers use "file:///C:/..." for files on the C: drive on windows.The windows path "\MACHINE\share\file" is represented as "file://MACHINE/share/file" in a QUrl.
I suspect that fromUserInput is matching the "C:" as a "host:port" pattern in that position in a generic URL, and dropping the : as it is redundant. In any case, fromUserInput is designed to guess what the user meant when they typed a non canonical URL.
-
I think if the QUrls needs to designate an existing file you should just check for that with QDir::exists. This will return false as well when the Url does not have a valid format. QUrl::isValid will only test that the url follows the url format, not that it actually points to something.