Why does the common file dialog change the current directory?

Raymond Chen

When you change folders in a common file dialog, the common file dialog calls Set­Current­Directory to match the directory you are viewing. (Don’t make me bring back the Nitpicker’s Corner.) Okay, the first reaction to this is, “What? I didn’t know it did that!” This is the other shoe dropping in the story of the curse of the current directory. Now the question is, “Why does it do this?” Actually, you know the answer to this already. Many programs require that the current directory match the directory containing the document being opened. Now, it turns out, there’s a way for you to say, “No, I’m not one of those lame-o programs. I can handle current directory being different from the document directory. Don’t change the current directory when using a common file dialog.” You do this by passing the OFN_NO­CHANGE­DIR flag. (If your program uses the IFile­Dialog interface, then NO­CHANGE­DIR is always enabled. Hooray for progress.) But now that you know about this second curse, you can actually use it as a counter-curse against the first one. If you determine that a program is holding a directory open, and you suspect that it is the victim of the curse of the current directory, you can go to that program and open a common file dialog. (For example, Save As.) From that dialog, navigate to some other directory you don’t plan on removing, say, the root of the drive, or your desktop. Then cancel the dialog. Since the common file dialog changes the current directory, you have effectively injected a Set­Current­Directory call into the target process, thereby changing it from the directory you want to remove. Note, however, that this trick works only if the application in question omits the OFN_NO­CHANGE­DIR flag when it calls Get­Save­File­Name.

In Explorer, you can easily call up a common file dialog by typing Win+R then clicking Browse, and in versions of Windows up through Windows XP, Explorer didn’t pass the OFN_NO­CHANGE­DIR flag.


Discussion is closed.

Feedback usabilla icon