1
$\begingroup$

For selecting a folder which contains data files I use the following code:

ChoiceDialog[{FileNameSetter[Dynamic[dir], "Directory"], Dynamic[dir]}];

dir (as string) is the full path name of the folder.

How can I extract the deepest folder name? For examples:

dir = "F:\\20160111\\data\\folder1";

I would like to extract "folder1".

Can that be read directly with ChoiceDialog? Or do I have to search in the dir string?

Example on how I do it:

dirLength = StringLength[dir];
start = StringPosition[dir, "\\"];
start = Max[Flatten[start]];
deepestFolder=StringTake[dir, -(dirLength - start)];

Print[deepestFolder]
"folder1"
$\endgroup$
2
  • 1
    $\begingroup$ Take a look at FileBaseName and friends. $\endgroup$
    – Kuba
    Commented Jan 20, 2016 at 13:33
  • $\begingroup$ Why so easy ;-) thanks ... $\endgroup$
    – mrz
    Commented Jan 20, 2016 at 14:14

1 Answer 1

2
$\begingroup$

Perhaps this will work for you.

With[{dir = $HomeDirectory},
  Module[{choice, result},
    choice = SystemDialogInput["Directory", dir];
    If[Head[choice] =!= String,
      choice,
      FileNameTake[choice, -1]]]]

Two points.

  1. dir can be set to whatever starting directory you like. No matter where you start you will be able to navigate the whole file system.
  2. If you are determined to stick with ChoiceDialog, you can still use FileNameTake extract the terminal directory in the returned path string.
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.