如何在我的 C# TreeView 中仅查看包含具有 ReadOnly 属性的 PDF 的目录?

How do I only view directories containing PDFs with ReadOnly attribute in my C# TreeView?

我的 C# 窗体中有一个 TreeView,我希望它仅显示包含非只读 PDF 的目录。文件也应该显示。

我当前的代码:

private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
    {
        var directoryNode = new TreeNode(directoryInfo.Name);
        foreach (var directory in directoryInfo.GetDirectories())
            directoryNode.Nodes.Add(CreateDirectoryNode(directory));
        foreach (var file in directoryInfo.GetFiles("*.pdf"))
            directoryNode.Nodes.Add(new TreeNode(file.Name));
        return directoryNode;
    }

目前我所知道的:

提前致谢。

您的逻辑在添加目录节点时存在一点缺陷,而没有先检查是否存在任何 read/write pdf 文件。

考虑到可能存在文件夹包含所有只读 pdf 文件但其子文件夹之一包含 read/write pdf 文件的情况,因此仅检查文件夹中是否存在 read/write pdf 文件当前目录也不够:

pdffolder
    pdf1 (read-write)
    pdf2 (read-write)
    sub1 (folder)
        pdf3 (read-only)
        sub1-1 (folder)
            pdf4 (read-write)

这种情况下,我们还是希望sub1可见,pdf3隐藏,因为我们希望sub1-1文件夹可以访问(因为下面有pdf4)

这是您的新方法。只有一个突破性的变化,就是现在这个方法可以 return NULL 如果没有 read/write pdf 文件在它下面和它的任何子文件夹下。

希望对您有所帮助。

private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
    TreeNode directoryNode = null;

    // First, check if there are any read/write files in this folder
    // and create the directory node if yes, and add the pdf file node too.
    foreach (FileInfo file in directoryInfo.GetFiles("*.pdf"))
    {
        if (!File.GetAttributes(file.FullName).HasFlag(FileAttributes.ReadOnly))
        {
            if (directoryNode == null)
            {
                directoryNode = new TreeNode(directoryInfo.Name);
            }
            directoryNode.Nodes.Add(new TreeNode(file.Name));
        }
    }

    // There can be no writeable pdf files, but we should still check
    // the sub directories for the existence of a writeable pdf file
    // because even if this directory does not have one, a sub directory may,
    // and in that case we want that pdf file to be accessible.
    foreach (DirectoryInfo directory in directoryInfo.GetDirectories())
    {
        TreeNode subDirectoryNode = CreateDirectoryNode(directory);
        // the sub directory node could be null if there are no writable
        // pdf files directly under it. Create, if one of the sub directories
        // have one.
        if (subDirectoryNode != null)
        {
            if (directoryNode == null)
            {
                directoryNode = new TreeNode(directoryInfo.Name);
            }
            directoryNode.Nodes.Add(subDirectoryNode);
        }
    }

    // The return value is null only if neither this directory 
    // nor any of its sub directories have any writeable pdf files
    return directoryNode;
}