我做了一个程序,应该显示一个文件系统树。我将其设置为显示 C:
中的文件系统。当我编译程序时,表示C:
拒绝访问。告诉我你需要什么,以防你帮助我,我会为你提供所需的信息。谢谢!
P.S。当我将程序设置为列出C:\Windows\
中的文件系统时,它可以工作。
这是我使用的代码:
private void ListDirectory(TreeView treeView, string path)
{
treeView.Nodes.Clear();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
}
private static TreeNodeCreateDirectoryNode(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())
directoryNode.Nodes.Add(new TreeNode(file.Name));
return directoryNode;
}
在程序中,ti调用我使用的方法:
mainWindow(){
InitialiseComponent();
ListDirectory(treeView1, @"C:\");
}
答案 0 :(得分:2)
此代码将在执行它的用户帐户下运行。根据该帐户的权限,某些目录(如用户帐户文件夹或回收站)可能会出现System.UnauthorizedAccessException
。
这不会阻止您在目录结构的中途导航,但会阻止该帐户读取受保护文件夹中的所有目录。
您可以使用directoryInfo.GetAccessControl()
或者你可以抓住System.UnauthorizedAccessException
。那么您的代码可能如下所示:
try
{
var directoryNode = new TreeNode( directoryInfo.Name );
foreach ( var directory in directoryInfo.GetDirectories() )
directoryNode.Nodes.Add( CreateDirectoryNode( directory ) );
foreach ( var file in directoryInfo.GetFiles() )
directoryNode.Nodes.Add( new TreeNode( file.Name ) );
return directoryNode;
}
catch ( System.UnauthorizedAccessException )
{
return new TreeNode( "Unavailable Node" );
}
catch ( System.IO.PathTooLongException )
{
return new TreeNode( "Unavailable Node" );
}