我看到了很多使用 TreeView 顯示現有檔案夾結構的示例,但我想做的是遵循 ->
我的 C# WinForms 中有一個標準檔案夾結構,其中包含多個檔案夾和子檔案夾以及一個組合框,用于顯示路徑中的現有檔案夾。
用戶應該能夠從我的組合框中選擇一個現有檔案夾,然后只需按一個按鈕即可在我的 TreeView 中創建每個選中的專案。
這是我現有的代碼:
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
foreach (TreeNode tn in pathLorem.Nodes)
{
tn.Expand();
}
DirectoryInfo obj = new DirectoryInfo("F:\\");
DirectoryInfo[] folders = obj.GetDirectories();
loremDropDown.DataSource = folders;
}
我不需要完成代碼,我只需要一個教程或現有的 StackOverflow 帖子。我現在正在尋找1小時。

uj5u.com熱心網友回復:
根據您的說明,您需要從給定目標路徑中的已檢查節點樹目錄結構中創建。
編輯建構式如下...
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
foreach (TreeNode tn in pathLorem.Nodes)
{
tn.Expand();
}
loremDropDown.DisplayMember = "Name";
loremDropDown.ValueMember = "FullName";
loremDropDown.DataSource = new DirectoryInfo("F:\\").GetDirectories();
}
創建一個遞回方法來獲取檢查的節點。
private IEnumerable<TreeNode> GetCheckedNodes(TreeNodeCollection nodeCol)
{
foreach (TreeNode node in nodeCol)
{
if (node.Checked ||
node.Nodes.Cast<TreeNode>().Any(n => n.Checked))
{
yield return node;
}
foreach (TreeNode childNode in GetCheckedNodes(node.Nodes))
{
if (childNode.Checked)
yield return childNode;
}
}
}
要創建目錄,Path.Combine目標路徑TreeNode.FullPath和替換TreeView.PathSeparator為Path.DirectorySeparatorChar.
private void SomeButton_Click(object sender, EventArgs e)
{
var destPath = loremDropDown.SelectedValue.ToString();
var treeSep = pathLorem.PathSeparator;
var dirSep = Path.DirectorySeparatorChar.ToString();
foreach (var node in GetCheckedNodes(pathLorem.Nodes))
{
var sPath = Path.Combine(destPath, node.FullPath.Replace(treeSep, dirSep));
Directory.CreateDirectory(sPath);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/506805.html
