Skip to content

Folder Contents in a Menu, Redux

Since I was asked for a few enhancements, here’s a quick update to my previous Folder Contents in a Menu post from earlier this week.

The requested enhancements are:

  • Display the requested folder in the menu.
  • Sort the folder contents.
  • Skip files that cannot be accessed.

To dive into these a bit more, right now when you request SpecialFolder.Documents, you see the contents of Documents. With a slight change, you can now see “Documents” as the top of the hierarchical menu.

The folder contents were previously shown in the default file system order, which seems pretty random. Now the files are sorted in alphabetical order.

Lastly, if you had any inaccessible files in your folder hierarchy, an IOException was raised (and not caught). Now any files that cause an IOException are skipped.

Here is the updated CreateFolderMenu method:

Private Function CreateFolderMenu(f As FolderItem, showRoot As Boolean = False) As MenuItem
   Var base As New MenuItem(f.Name, f)
   Var rootMenu As MenuItem
   If showRoot Then
     rootMenu = New MenuItem(f.Name, f)
   End If

   Var sortedFiles() As FolderItem
   Var sortedNames() As String

   For i As Integer = 0 To f.Count - 1
     Try
       Var child As FolderItem
       child = f.ChildAt(i)
       sortedFiles.Add(child)
       sortedNames.Add(child.Name)
     Catch e As IOException
       Continue // Skip any unavailable files
     End Try
   Next

   sortedNames.SortWith(sortedFiles)
   For Each child As FolderItem In sortedFiles
     If child.IsFolder Then
       base.AddMenu(CreateFolderMenu(child))
     Else
       Var m As New MenuItem(child.Name, child)
       base.AddMenu(m)
     End If
   Next

   If showRoot Then
     rootMenu.AddMenu(base)
     Return rootMenu
   End If

   Return base
 End Function

You’ll notice a new parameter, showRoot. Pass in True to include the root folder name in the hierarchical menu.

The sorting demonstrates the use of the SortWith command which allows you to sort one array (in the case an array of file names) and keep another array (the array of actual FolderItems) correspondingly sorted.

The Try…Catch is used to catch an IOException on a file and then allows things to continue on to the next file.

Download the Project