浏览文件夹时筛过滤选系统无权限、隐藏、系统、临时文件夹

有时在遍历系统文件夹时,对于系统的隐藏的某些文件无法访问,需要提前判断过滤

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

 

posted @ 2020-07-15 09:28  逯文杰  阅读(282)  评论(0编辑  收藏  举报