DirectoryInfoクラスを使用して、特定のルート フォルダのすべてのサブディレクトリのリストを取得できます。サブディレクトリで再帰検索を実行し、そのデータを使用してメニューを作成する必要があります。
以下に、この作業を行うコードをいくつか示します。menuStrip1 という MenuStrip が既にあることを前提としています。
public void BuildMenu()
{
//first we get the DirectoryInfo for your root folder, this will be used to find the first set of sub-directories
DirectoryInfo dir = new DirectoryInfo(@"C:\MyRootFolder\");//Change this
//next we create the first MenuItem to represent the root folder, this is created using the GetMenuItem function
ToolStripMenuItem root = GetMenuItem(dir);
//we add our new root MenuItem to our MenuStrip control, at this point all sub-menu items will have been added using our recursive function
menuStrip1.Items.Add(root);
}
public ToolStripMenuItem GetMenuItem(DirectoryInfo directory)
{
//first we create the MenuItem that will be return for this directory
ToolStripMenuItem item = new ToolStripMenuItem(directory.Name);
//next we loop all sub-directory of the current to build all child menu items
foreach (DirectoryInfo dir in directory.GetDirectories())
{
item.DropDownItems.Add(GetMenuItem(dir));
}
//finally we return the populated menu item
return item;
}
ルート フォルダのパスを変更することを忘れないでください。
注: Yorye Nathan は、ショートカット フォルダについて良い点を指摘しています。フォルダーのいずれかが親フォルダーへのショートカットである場合、無限ループが発生します。これを解決する最も簡単な方法は、構造にショートカットが含まれていないことを確認することです。このアプリケーション用に特別に構築された構造を持っていると仮定すると、これは簡単なオプションかもしれません。ただし、これをユーザー定義のルート フォルダーで実行している場合は、これらを確認する必要があります。
GetMenuItem
.Net 3.5 以降 (LINQ + オプションのパラメーター) を想定して、これを考慮して以下のように関数を変更できます。
public ToolStripMenuItem GetMenuItem(DirectoryInfo directory, List<DirectoryInfo> currentFolders = null)
{
if (currentFolders == null)
currentFolders = new List<DirectoryInfo>();
currentFolders.Add(directory);
ToolStripMenuItem item = new ToolStripMenuItem(directory.Name);
foreach (DirectoryInfo dir in directory.GetDirectories())
{
if (!currentFolders.Any(x => x.FullName == dir.FullName))//check to see if we already processed this folder (i.e. a unwanted shortcut)
{
item.DropDownItems.Add(GetMenuItem(dir, currentFolders));
}
}
return item;
}