有时在遍历系统文件夹时,对于系统的隐藏的某些文件无法访问,需要提前判断过滤
public void GetDirectoryFold(string Path,TreeNode rootNode)
{
DirectoryInfo directory = new DirectoryInfo(rootNode.Tag.ToString());
try
{
foreach (DirectoryInfo dir in directory.GetDirectories())
{
{
#region //对系统的、临时的、隐藏文件夹判断筛选不处理
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
continue;
}
else if ((dir.Attributes & FileAttributes.System) == FileAttributes.System)
{
continue;
}
else if ((dir.Attributes & FileAttributes.Temporary) == FileAttributes.Temporary)
{
continue;
}
else if (dir.Attributes != FileAttributes.Directory)
{
continue;
}
if (!hasWriteAccessToFolder(dir.FullName))
{
continue;
}
#endregion
else
{
TreeNode dirNode = new TreeNode();
dirNode.Tag = dir.FullName;
dirNode.Text = dir.Name;
dirNode.SelectedImageIndex = IconIndex.OpenFold;
dirNode.ImageIndex = IconIndex.CloseFold;
rootNode.Nodes.Add(dirNode);
GetDirectoryFold(dir.FullName, dirNode);
}
}
}
}
catch(Exception ex)
{
throw ex;
}
}
#region //判断是否有权限访问文件夹
private bool hasWriteAccessToFolder(string PathFolder)
{
try
{
System.Security.AccessControl.DirectorySecurity directorySecurity = Directory.GetAccessControl(PathFolder);
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
#endregion