Folder Recursion with C#
Some applications must read the folder structure beneath an existing folder or for an entire disk or attached device. The standard method in the Directory class can cause problems when used in this way. An alternative is to recursively read the folders.
Reading Folders
It is common to wish to read the entire folder structure of a disk when you are creating software that works with the file system. For example, you may wish to populate a TreeView control with the complete list of directories, or you might read the folders in order to compare them with another directory or with a backup copy.
The Directory class, which is a standard type within the .NET framework, includes a method, named GetDirectories, that allows you to read the folders within a given path, returning their names in a string array. You can use further methods of the Directory and File classes to work with the folders and their contents. An example of the GetDirectories method is shown below. This returns a list of folder names that can be found in the root of the C: drive.
NB: To run this code you need to reference the System.IO namespace so add the directive, "using System.IO;" to your code.
string[] folders = Directory.GetDirectories(@"c:\");
To instruct the method to work recursively, reading the folders, their subfolders and directories beneath these until the folder structure is exhausted, you can add the AllDirectoriessearch option, as shown below:
string[] folders = Directory.GetDirectories(@"c:\", "*", SearchOption.AllDirectories);
Unfortunately, this has problems. Key amongst these is that some of the folders that you attempt to read could be configured so that the current user may not access them. Rather than ignoring folders to which you have restricted access, the method throws anUnauthorizedAccessException. However, we can circumvent this problem by creating our own recursive folder search code.
Folder Recursion
Let's start with some simple folder recursion code that recreates the flawed functionality of the GetDirectories method. We'll create it within a console application and show its activity by outputting folder name as they are examined. In a real application you could build and return a list or array, or use an iterator to return the values as they are required, thus avoiding the delay caused by reading large folder structures ahead of the time they are needed.
The code below shows the basic recursive method. The Main method callsShowAllFoldersUnder, passing in the starting path. In this case we are going to display all folders starting from the root of the C: drive.
ShowAllFoldersUnder does the real work. When this method is called it uses the basic version of GetDirectories to obtain the folder list for directories immediately within the provided path. It then loops through these folders, first displaying the name, then calling itself, passing the folder name, to look one level deeper. This recursive nature causes all folders to be examined, unless an exception is thrown.
static void Main(string[] args)
{
Console.WriteLine(@"c:\");
ShowAllFoldersUnder(@"c:\", 0);
} private static void ShowAllFoldersUnder(string path, int indent)
{
foreach (string folder in Directory.GetDirectories(path))
{
Console.WriteLine("{0}{1}", new string(' ', indent), Path.GetFileName(folder));
ShowAllFoldersUnder(folder, indent + 2);
}
}
To avoid UnauthorizedAccessExceptions stopping the execution, we need to add a try / catch block around the foreach loop. We can use this to catch only that type of exception and ignore it. This means that the folders to which the user does not have access will not be displayed. The updated ShowAllFolders code is as follows.
private static void ShowAllFoldersUnder(string path, int indent)
{
try
{
foreach (string folder in Directory.GetDirectories(path))
{
Console.WriteLine("{0}{1}", new string(' ', indent), Path.GetFileName(folder));
ShowAllFoldersUnder(folder, indent + 2);
}
}
catch (UnauthorizedAccessException) { }
}
Reparse Points
Something else that we must deal with is reparse points, or junction points. Most disks used by Windows operating systems are formatted using the New Technology File System, or NTFS. This allows disks to be mounted in interesting ways. In addition to the usual assignment of drive letters, such as C:, disks can be mounted within folders. This means that when you use Windows Explorer to browse to the C:\OtherDisk folder, you may be seeing the contents of another disk or partition altogether.
Junction points generate a problem when recursively scanning folders; drives can be mounted in such a way as to create infinite directory structures. For example, the disk containing your C: drive could be mounted within a folder named, "C:\Infinite". If you looked inside this folder you would find everything that is in the root of C:, including the "Infinite" folder. You could continue to drill down into that folder, each time seeing the same subfolders and files.
To avoid infinite loops, we need to check that a folder is not a junction point. We can do this by reading each folder's attributes and checking if it is a reparse point. To get the attributes we use the File.GetAttributes method, which returns an enumeration that represents a bit field. We can then use the bitwise AND operator to check for the existence of the ReparsePointflag.
Using this information we can create the final version of ShowAllFoldersUnder, as follows:
private static void ShowAllFoldersUnder(string path, int indent)
{
try
{
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint)
!= FileAttributes.ReparsePoint)
{
foreach (string folder in Directory.GetDirectories(path))
{
Console.WriteLine(
"{0}{1}", new string(' ', indent), Path.GetFileName(folder));
ShowAllFoldersUnder(folder, indent + 2);
}
}
}
catch (UnauthorizedAccessException) { }
}
Folder Recursion with C#的更多相关文章
- VSCode中使用vue项目ESlint验证配置
如果在一个大型项目中会有多个人一起去开发,为了使每个人写的代码格式都保持一致,就需要借助软件去帮我们保存文件的时候,自己格式化代码 解决办法:vscode软件下载一个ESLint,在到设置里面找到se ...
- Visual Basic 函数速查
Calendar 常数 可在代码中的任何地方用下列常数代替实际值: 常数 值 描述 vbCalGreg 0 指出使用的是阳历. vbCalHijri 1 指出使用的是伊斯兰历法. Color 常数 可 ...
- VMWare Tools 和 Shared folder(共享文件夹)
转自: http://www.51testing.com/html/38/225738-143732.html 使用vmwar下shared folders功能实现vmware中host与ghost间 ...
- eclipse的package, folder, source folder 异同以及相互转化
1 相同点:都是文件夹; 不同点: 我们用面对对象思维来看; 首先说folder, 三者的父类(object),就是普通的文件夹,它和我们window下面使用的文件夹没有任何区别; source fo ...
- 怎样制作web版的folder treeview
文件夹treeview的效果 这样的treeview在实际项目中使用的场景较多. 既然用的多,那就DIY一遍,虽没有面面俱到,但也要将其基本实现完成一遍. 1.先准备图标素材 file.gif,文件 ...
- iOS项目groups和folder的区别(组和文件夹)
在引用一个第三方框架的时候,已经拖进去了,但是引用框架里面的文件时,竟然报错说找不到.......查了一下,原来在拖进去时没有注意group和folder的选择! 其实仔细观察一下,不难发现,以gro ...
- push or get File or Folder using scp wrapped with expect and bash
经常需要把服务器的某些文件传到 Mac,或者获取 Mac 的一些文件到服务器.尽管有很多命令scp, ftp, rsync都可以,霸特每次都有敲好长的命令,好烦,而且还要输入密码.所以想着 wrap ...
- Python递归报错:RuntimeError: maximum recursion depth exceeded in comparison
Python中默认的最大递归深度是989,当尝试递归第990时便出现递归深度超限的错误: RuntimeError: maximum recursion depth exceeded in compa ...
- folder、source folder、package 区别与联系
在eclipse下,package,source folder,folder都是文件夹. 它们的区别如下: package:当你在建立一个package时,它自动建立到source folder下 ...
随机推荐
- 详解 Windows 8.1 下的按流量计费的使用
用过 Windows 8 ,而且用过手机热点的同学应该都不陌生,Windows 会自动识别这个Wifi是按流量计费的.然后会限制流量. 在正式说怎么用之前,我们先啦讨论一下按流量计费网络. 有线网络无 ...
- C#开发中使用Npoi操作excel实例代码
C#开发中使用Npoi操作excel实例代码 出处:西西整理 作者:西西 日期:2012/11/16 9:35:50 [大 中 小] 评论: 0 | 我要发表看法 Npoi 是什么? 1.整个Exce ...
- HTML5 Canvas rect()和strokeRect() 的区别
看到 Canvas rect()和strokeRect()时,发现这俩效果一样.仔细区分后发现: 他们都接受相同的参数,但rect() 只是创建一个矩形,并不绘制,如图: 要看到实际效果需要使用 st ...
- struts2的运行原理及配置文件
struts2官方运行原理图: 1,客户发送请求(url地址就是请求),tomcat接到请求会找到相应的应用web.xml配置文件. 2,web.xml中filter拦截器把你的请求接收到,并进入Fi ...
- (译)cocos2d-x跨android&ios平台开发入门教程
免责申明(必读!):本博客提供的所有教程的翻译原稿均来自于互联网,仅供学习交流之用,切勿进行商业传播.同时,转载时不要移除本申明.如产生任何纠纷,均与本博客所有人.发表该翻译稿之人无任何关系.谢谢合作 ...
- du -sg 和df -g 所看的文件系统大小不一致
最近碰到一个问题: df -g 查看内存,发现空间已经满了,但是到对应目录查看,发现只用了一半的空间,感觉还有一半不见了. 经咨询其他人,给了两个解释: 1.fsck :使用Fsck命令修复损坏的分区 ...
- 从DB灌值到DataTable时,字段值为NULL时报错相关信息;
报错信息: 1. 2. 3. 4. 5. 6. 解决方法: 1. Data Layer SQL 语句取数据时,把其列值有为null的字段用0.00替换,(ISNULL的用法): 2. #r ...
- Gradle的属性设置大全
Gradle作为一款项目构建工具,由于其强大.灵活.快速.完全兼容Ant等特性,越来越受到人们欢迎.Gradle的灵活有时候也会引起人们的困惑.比如在Gradle中设置变量和属性就有N种办法.由于Gr ...
- JavaScript this 总结(含 ES6)
本文主要总结自<JavaScript 语言精粹>.部分总结自<JavaScript 高级程序设计>以及自己的经验 四种调用模式 在 JavaScript 中,this 的值取决 ...
- atitit.ajax bp dwr 3.的注解方式配置使用流程总结.....
atitit.ajax bp dwr 3.的注解方式配置使用流程总结..... 1. 下载 dwr.jar 1M 1 2. 配置注解方式..web.xml 1 3. Class 配置 2 4. 测试 ...