October 6th, 2023

A very belated improvement to the filtering of the Browse for Folder dialog so it shows only drive letters

Quite some time ago, I showed how to filter the Browse for Folder dialog so it shows only drive letters. There’s a small quirk in the code, which it has taken me several years to getting around to addressing.

But hey, better late than never.

To recap, we detected drive letters by verifying that the length is at most 4, and that it is reported as a root directory by Path­IsRoot. While this successfully allows drives A:\ through Z:\, the Path­Is­Root function also reports \\a through \\z as roots if you had a server with a one-character name. It also reports \ as a root, which is I guess sort of true?

Now, these aren’t problems in practice because you cannot add \\a or \ as children of My Computer, or at least, you can’t do it today. But just to make sure, let’s reject those cases.

Fortunately, the fix is simple: Instead of using PathIsRoot, we switch to PathGetDriveNumber, which returns −1 if the path does not begin with a letter and a colon.

    if (SUCCEEDED(StrRetToBuf(&str, pidlItem, buf, ARRAYSIZE(buf))) &&
        /* PathIsRoot(buf) */
        PathGetDriveNumber(buf) >= 0) return S_OK;

There is still a tiny hole here: If someday it becomes possible to add raw drive letters to My Computer, then this will accept A: as well as A:\. I’m not sure what that would even mean, but you could wear a belt and suspenders by using Path­Is­Root to verify that you got a root, and then using Path­Get­Drive­Number to verify that you got a drive.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

2 comments

Discussion is closed. Login to edit/delete existing comments.

Newest
Newest
Popular
Oldest
  • skSdnW · Edited

    \ is a relative path. It’s unfortunate that it is also considered a root.

    It is very rare that \\server is useful when dealing with paths, \\server\share is what you want (PathIsUNCServerShare).

  • dasfas dfa

    yes,you are right

Feedback