65.9K
CodeProject 正在变化。 阅读更多。
Home

文件系统树形视图

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.76/5 (26投票s)

2005年6月29日

2分钟阅读

viewsIcon

180449

downloadIcon

3610

一个用于 .NET 的文件系统树形视图。

Screenshot

引言

.NET 1.1 中没有文件系统树形视图! 因此我最终自己制作了一个。 这是文件系统树形视图的一个非常基础的版本。 还可以添加许多其他方法和/或属性,以使此控件更有用。 但是,我发布此控件的目的是为了节省某人的时间和精力。

处理递归和极其庞大的文件系统时,性能通常是一个问题。 因此,为了克服这个问题,我设计了这个树形视图组件,使其按需加载。 为了实现这一点,我最初只加载根目录和文件。 显然,文件不能有任何子节点,但目录另一方面可以包含子目录和文件。 如果一个目录有子目录和/或文件,我添加了我在描述中称为“假子节点”的东西。 基本上,这意味着我在“目录节点”中添加一个子树节点,以便在其前面显示“+”加号。 这表示用户可以进一步深入查看子目录和文件。 这里有一些示例代码

int fileCount = 0;

if( this.TreeView.ShowFiles == true )
    //get a file count
    fileCount = this._directoryInfo.GetFiles().Length;         

//if the directory contains 
//sub-items then add a fake child node to 
//indicate to the user that they can drill down
if( (fileCount + this._directoryInfo.GetDirectories().Length) > 0 )
    new FakeChildNode( this );

FakeChildNode 类非常简单。 它继承自 TreeNode 类,并且只有一个构造函数,该构造函数将子节点添加到现有节点。

public class FakeChildNode : TreeNode
{
    public FakeChildNode( TreeNode parent ) : base()
    {
        parent.Nodes.Add( this );
    }
}

因此,现在我们已经加载并虚拟化了初始目录,我们可以编写控制子节点按需加载的代码。 为了做到这一点,我为树形视图的“BeforeExpand”事件编写了一个事件处理程序。

void FileSystemTreeView_BeforeExpand(object sender, 
                           TreeViewCancelEventArgs e)
{
    //if node is of type filenode then get out of event
    if( e.Node is FileNode ) return;
        
    DirectoryNode node = (DirectoryNode)e.Node;

    //checks to see if the node has already 
    //been loaded. Basically this just checks to 
    //see if the first child is of type "FakeChildNode"
    if (!node.Loaded)
    {
        //remove the fake child node used for virtualization
        node.Nodes[0].Remove();
        //Load sub-directories and files
        node.LoadDirectory();
        if( this._showFiles == true )
        node.LoadFiles();
    }
}

因此,现在您已经了解了此控件的基本逻辑,这里有一个关于如何使用它的示例

使用代码

C2C.FileSystem.FileSystemTreeView tree = 
             new C2C.FileSystem.FileSystemTreeView();         
Controls.Add( tree );
tree.Dock = DockStyle.Fill;
//if you want to view only folders 
//you can set the ShowFiles property to true
//tree.ShowFiles = false; 
tree.Load( @"C:\" );
© . All rights reserved.