I have currently the following problem. I have a directory structure like
root
- level 1
- level 1.1
- level 1.2
- level 2
- level 2.1
- level 3
- level 4
- level 4.1
from this I want to build a menu. so root will be the menu item to click on and all the level will be needed to drill down to the information you want to get.
As I’m pretty new to C# (not programming) I wanted to know if there is any help from .NET for this task. I don’t want to start to fiddel around with code that is already there…
Thanks for any input!
You can use the DirectoryInfo class to obtain a list of all sub-directories for a given root folder. You should the perform a recursive search on sub-directories and build your menu using that data.
Here is some code that will do the job for you, it assumes you already have a MenuStrip called menuStrip1:
Dont forget to change the root folder path!
NOTE: Yorye Nathan has made a good point about short-cut folders. If any of your folders is a short-cut to a parent folder this will cause an endless loop. The easiest way to solve this is to make sure your structure doesn’t contain any short-cuts. This may be an easy option for you assuming you have a specifically built structure for this application. If however, you are running this on a user-defined root folder you will want to check for these.
You could modify the
GetMenuItemfunction as below to account for this, assuming .Net 3.5 or higher (LINQ + optional parameters):