Reputation:
I made a program tat should display a filesystem tree. I set it to display the filesystem from C:
. When I compile the program says that access is denied for C:
. Tell me what would you need in case you would help me and I will provide you the required information. Thanks!
P.S. When I set the program to list the filesystem in C:\Windows\
it worked.
This is the code that I used:
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;
}
In the program, ti call the method I used:
mainWindow(){
InitialiseComponent();
ListDirectory(treeView1, @"C:\");
}
Upvotes: 2
Views: 888
Reputation: 993
This code will run under the user account that is executing it. Based on the permissions of that account a System.UnauthorizedAccessException
may occur for some directories such as a user account folder or the recycle bin.
This will not prevent you from navigating partway through the directory structure, but would prevent that account from reading all of the directories inside of the protected folders.
You could write code to pull the access control list using directoryInfo.GetAccessControl()
Or you could catch the System.UnauthorizedAccessException
. Then your code might look like this:
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" );
}
Upvotes: 2