Reputation: 1489
After a call of GetOpenFileName
the current directory of the process changes to the directory of the file opened file by the GetOpenFileName
.
How can I keep the default current directory instead ?
Upvotes: 8
Views: 1788
Reputation: 598384
How can I keep the default current directory instead ?
If you read the OPENFILENAME
documentation, there is an OFN_NOCHANGEDIR
flag for that exact purpose:
Restores the current directory to its original value if the user changed the directory while searching for files.
Despite what the documentation claims, this flag is supported in GetOpenFileName()
.
Also see Raymond Chen's blog article on this subject:
Why does the common file dialog change the current directory?
Upvotes: 12
Reputation: 36348
The current directory exists because it is very convenient for command line tools. It generally isn't very much use for GUI applications, which is probably why Microsoft's developers didn't worry about allowing GetOpenFileName() to change it. There is of course the occasional edge case, and you might be dealing with one of them, although it is hard to tell from your question as written. (Are you absolutely sure that you want the current directory and not, for example, the directory containing your executable?)
At any rate, if you do want the current directory, the safest approach is to retrieve it as soon as the program starts, and use that saved value to construct fully qualified paths. Don't just restore the original current directory whenever you think it might have been changed, build the fully qualified paths yourself. This is especially important in multi-threaded code, or in code that might need to be multi-threaded in the future (i.e., pretty much everything) but it also eliminates the risk of overlooking one or more code paths where the current directory might change.
Upvotes: 4