Limit Directories in TFileOpenDialog

I am using TFileOpenDialog in the data entry form in Delphi XE. The user selects the PDF document in the dialog box, and the UNC path and file name are stored in the database field. I want to limit the area in which the user views the DefaultDirectory property and the files / subdirectories below this. I hope that the user will not be able to select files that are on local disks or mapped disks, inaccessible to other users who need values ​​stored in the database.

I think the way to do this is with the TFileOpenDialog.OnFolderChanging event. But I'm not sure how to check if the selected file or folder is a child of the DefaultDirectory. Given a file name or directory name, how can I determine if it depends on DefaultDirectory?

+4
source share
2 answers

you can compare the ShellItem TFileOpenDialog property ShellItem TFileOpenDialog property using StartsText and set the CanChange value according to the result.

check this sample.

 uses StrUtils, ActiveX, ShlObj; {$R *.dfm} procedure TForm50.Button1Click(Sender: TObject); begin FileOpenDialog1.DefaultFolder:='C:\Program Files'; FileOpenDialog1.Execute; end; function GetItemName(Item: IShellItem; var ItemName: TFileName): HResult; var pszItemName: LPCWSTR; begin Result := Item.GetDisplayName(SIGDN_FILESYSPATH, pszItemName); if Failed(Result) then Result := Item.GetDisplayName(SIGDN_NORMALDISPLAY, pszItemName); if Succeeded(Result) then try ItemName := pszItemName; finally CoTaskMemFree(pszItemName); end; end; procedure TForm50.FileOpenDialog1FolderChanging(Sender: TObject;var CanChange: Boolean); var CurrentDir : TFileName; Result : HRESULT; begin Result := GetItemName(TFileOpenDialog(Sender).ShellItem,CurrentDir); CanChange := Succeeded(Result) and StartsText(TFileOpenDialog(Sender).DefaultFolder,CurrentDir); if not CanChange then ShowMessage('Sorry do you not have access to this folder'); end; 
+4
source

Just think along with what you are trying to do here ...

You can always let the user select a folder and then show an error if the wrong path was selected. After that, return the user to the root of the correct folder tree.

Benefits:

  • You can do your own check. You may have several start folders, or you may have more complex templates in what you accept and what not.

  • You can tell your users what you want from them, instead of banning what is not allowed. In modern user interface templates, he recommended that the buttons not be disabled, but so that the user could click it and then tell the user why some operation could not be performed. Otherwise, users may not understand why they cannot do certain things.

0
source

All Articles