# How to create a simple interface to get file path and execute some code on it?

I need to create a simple user interface to choose one file in the notebook directory, import it and execute some functions on the imported data. For the first version I created this code:

Button["get File Path",
];
function[fileData]


Now I want it to be a little bit more error proof, so if you cancel your selection, you don't get an error, and the rest of your code is not executed.

Button["get File Path",
fileData=Quiet@Check[Import@SystemDialogInput["FileOpen",NotebookDirectory[]],$Canceled] ] If[fileData!=$Canceled,function[fileData]]


I don't feel that it is the best practice for this kind of situation. Some clue to make the code more intelligent? Maybe with Module, DynamicModule, Return or something else?

-
For slow actions Button needs the option Method->"Queued" (see wolfram.com/xid/0mrh4y-k6ay1g) –  Sjoerd C. de Vries Oct 25 '12 at 8:53

First, you have to specify file for filename and only load file (with load, that can be e.g. Import), if file is not $Canceled (use UnsameQ instead of NotEqual). You have to put the loading after the test inside the button as well - after all, import should happen only when the button is pushed and the user has chosen a valid file. Also it is good practice to have initial values for file, fileData and dir. You can extract the actual directory that the user has chosen and feed it to SystemDialogInput so that next time the dialog is called it will open at the last used directory, for convenience. After some adjustments: fileData = {}; file = ""; dir =$UserBaseDirectory;

Button["get File Path",
"FileOpen", {dir, {"Mathematica files" -> {"*.nb", "*.m"}, "all files" -> {"*.*"}}},
WindowTitle -> "Open Mathematica file..."];
fileData = If[file =!= \$Canceled, load[file], "Nothing"];
]
Dynamic@fileData

-
Thanks @Murta, done! –  István Zachar Oct 25 '12 at 12:33
Nice!.. You got my point! Tks –  Murta Oct 25 '12 at 20:52

You could use FileNameSetter which seems a better choice for setting the path. If you have a DynamicWrapper containing your function call, it will be run every time the path is changed. When the user cancels, the path doesn't change, so it won't trigger anything or require special handling. Here I just use a dummy work function which prints the chosen files name.

function[file_]:=Print@FileBaseName@file

DynamicModule[{file = ""},
DynamicWrapper[
FileNameSetter[Dynamic[file], "Open", {"Notebook" -> {"*.nb"}}],
If[file != "", function[file]]
]]

-
I get an error when I try to use your code. It happens when I choose some file. –  Murta Oct 25 '12 at 0:01
@Murta What error? –  jVincent Oct 25 '12 at 9:00
It prints the file name in the error dialog box, not in the notebook. –  Murta Oct 25 '12 at 11:20