我在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;
}
到目前为止我所知道的:
((attributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly) == true
ReadOnly(R), Hidden(H), Archived(A), System(S)
,但我不确定如何使用它们。提前谢谢。
您的逻辑在添加目录节点时没有先检查任何读/写pdf文件是否存在缺陷。
考虑到文件夹可能包含所有只读pdf文件,而其子文件夹之一包含读/写pdf文件,仅检查当前目录中是否存在读/写pdf文件也是不够的:
pdffolder
pdf1 (read-write)
pdf2 (read-write)
sub1 (folder)
pdf3 (read-only)
sub1-1 (folder)
pdf4 (read-write)
在这种情况下,我们仍然希望sub1可见,而pdf3隐藏,因为我们希望sub1-1文件夹是可访问的(因为它下面有pdf4)
这是您的新方法。只有一个重大更改,即,如果该方法下及其任何子文件夹下都没有读/写pdf文件,则此方法可以返回NULL。
希望这会有所帮助。
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;
}