5

I'm using MFC's CFileDialog to select a file. I'm only interested in the complete file path as my application is not going to open it directly. Though the file dialog denies selecting the file by stating: "You don't have read permission to open this file". (Which is correct -- I don't have read permission; I don't want to open the file.)

So, is there a way under Windows to get to the path by using a file dialog?

Here's my code:

CFileDialog dlg(true, nullptr, nullptr, OFN_FILEMUSTEXIST, nullptr, nullptr, 0, true);
dlg.DoModal();
Markus Nißl
  • 371
  • 3
  • 10
  • I think that shouldn't happen unless `OFN_NOREADONLYRETURN` is set. Show the code you are using for `CFileDialog`. – Barmak Shemirani Jul 22 '15 at 07:46
  • @BarmakShemirani No, `OFN_NOREADONLYRETURN` is not set. I've just updated my post with sample code. – Markus Nißl Jul 22 '15 at 08:10
  • Try adding OFN_READONLY – Hans Passant Jul 22 '15 at 09:26
  • @HansPassant `OFN_READONLY` does not help. I have neither the intent to write, nor to read the file. I don't want to open it at all! – Markus Nißl Jul 22 '15 at 12:16
  • Did you try to inherit from CFileDialog and to override `virtual BOOL OnFileNameOK( );`? – Slava Jul 23 '15 at 21:13
  • @Slava I tried that as well but to no avail. As the MSDN documentation reads: _"Normally, you do not need to use this function because the framework provides default validation of filenames and displays a message box if an invalid filename is entered."_ The filename is not invalid! The overridden method was not even called as the dialog first prompted with "no read permission". – Markus Nißl Jul 26 '15 at 05:55

2 Answers2

2

I found a workaround by (ab)using the save file dialog which does not check if you have read/write permission to a file:

CFileDialog dlg(false, nullptr, nullptr, OFN_FILEMUSTEXIST, nullptr, nullptr, 0, true)

One might want to change the title of the dialog as the application won't save anything to the selected file:

dlg.m_ofn.lpstrTitle = "Select file";

Markus Nißl
  • 371
  • 3
  • 10
1

The file open dialog implements OFN_FILEMUSTEXIST by attempting to open the file.

If you don't have read permission to open the file, this will fail.

The solution is to not use the OFN_FILEMUSTEXIST flag, and implement your own check if needed (you could either do this after the dialog closes, or before it closes by using a hook).

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
  • Omitting `OFN_FILEMUSTEXIST` doesn't yield to another result -- I still get the prompt regarding missing permission to read the file. – Markus Nißl Jul 22 '15 at 12:14