问题:
在开发资源管理器时,需要在Form左下的TreeView中显示一级一级的文件夹及子文件夹,发现如下错误:
对路径“C:\Users\user\Documents\My Music”的访问被拒绝。
原代码:
//添加【我的文档】里的子节点
string myDocumentFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
DirectoryInfo myDocumentFolder = new DirectoryInfo(myDocumentFolderPath);
DirectoryInfo[] folders = myDocumentFolder.GetDirectories();
//MessageBox.Show(folders[9].Attributes.ToString());
foreach (DirectoryInfo folder in folders)
{
TreeNode node = new TreeNode(folder.Name);
node.ImageKey = "folder.ico";
node.SelectedImageKey = "folder.ico";
ndMyDocument.Nodes.Add(node);
//if (folder.Attributes.ToString().Contains("Hidden"))
//{
// continue;
//}
DirectoryInfo[] subFolders = folder.GetDirectories();
foreach (DirectoryInfo subFolder in subFolders)
{
TreeNode subNode = new TreeNode(subFolder.Name);
subNode.ImageKey = "folder.ico";
subNode.SelectedImageKey = "folder.ico";
node.Nodes.Add(subNode);
}
}
分析:
通过“MessageBox.Show(folders[11].Attributes.ToString());”发现My Music文件夹为隐藏文件。
解决办法:
if (folder.Attributes.ToString().Contains("Hidden"))
{
continue;
}
(原代码注释部分)