Dynamic Menu based on a folder

Pencillius

New member
Joined
Jul 29, 2006
Messages
4
Programming Experience
Beginner
Hi all,

I'm busy trying to write a sub that will add items to a menu based on the contents of a folder.

The general idea would be that the menu will add submenus where the are sub directories and links to files will generate where there are files. I dunno if this explination is very good...

Any suggestions on how best to go about doing this would be greatly appreciated, Currently I'm fiddiling around with the .IO names space and some of its properties, but I'm not having much success :confused:

Thanks in advance :D
 
Here is my code example, no code comments because it's self explaining :)
The general idea is to use a standard recursive method, using System.IO methods to get files and folders, and knowing the MenuStrip control.
In form I have added a Menustrip, and to that a menuitem 'FolderRootToolStripMenuItem'.

This method start the setup with a chosen folder:
VB.NET:
Private Sub setupFolderMenu()
  Dim folder As New IO.DirectoryInfo("..\..")
  FolderRootToolStripMenuItem.DropDownItems.Clear()
  addMenuItems(folder, FolderRootToolStripMenuItem)
End Sub
This method is called and also call itself recursively for each subfolder:
VB.NET:
Private Sub addMenuItems(ByVal folder As IO.DirectoryInfo, ByVal menuRoot As ToolStripMenuItem)
For Each fsi As IO.FileSystemInfo In folder.GetFileSystemInfos
  Dim menuItem As New ToolStripMenuItem(fsi.Name)
  menuRoot.DropDownItems.Add(menuItem)
  If TypeOf fsi Is IO.FileInfo Then
    menuItem.Tag = fsi.FullName
    AddHandler menuItem.Click, AddressOf fileMenuItem_click
  Else
    addMenuItems(fsi, menuItem)
  End If
Next
End Sub
This method is called when clicking a file menu item:
VB.NET:
Private Sub fileMenuItem_click(ByVal sender As Object, ByVal e As EventArgs)
  Dim ti As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
  If IO.File.Exists(ti.Tag) Then Process.Start(ti.Tag)
End Sub
 
Thanks!!!

Thanks JohnH!

This helps soooooo much! I've adapted a bit where needed but it really helped me understand how to use the blasted IO namespaces properly!:eek:

Again thanks alot
:D:D:D:D:D
 
Back
Top