简体   繁体   English

在C#中递归搜索目录

[英]Recursively search directories in C#

I need to recursively traverse directories in C#. 我需要以递归方式遍历C#中的目录。 I'm doing something like this . 我在做类似这样 But it throws exception when iterating through system folders. 但是在迭代系统文件夹时抛出异常。 How to check it before exception is thrown? 如何在抛出异常之前检查它?

You would have to check the access rights, but I would urge to to catch the exceptions instead, that makes the code easier to understand and would also deal with other issues like when you want to parse directories remotely and network gets down... 您将不得不检查访问权限,但我希望能够捕获异常,这使得代码更容易理解,并且还会处理其他问题,例如当您想远程解析目录并且网络崩溃时......

If you make a GUI for a directory tree you could also add some nice Lock icons on the places where you get access right exceptions and Error icons elsewhere... In C# there is already a nice free open source component for starting that. 如果您为目录树制作GUI,您还可以在其他地方获得访问权限异常和其他错误图标的地方添加一些漂亮的锁定图标...在C#中已经有一个很好的免费开源组件来启动它。

If you want to count files and sizes there is no way to overcome the rights issue, you have to run your tool under a more privileged user. 如果要计算文件和大小,则无法克服权限问题,则必须在更高权限的用户下运行工具。

I took a look at your link, and the code. 我看了你的链接和代码。 In the code sample, the try...catch construct is used to just stop searching when you get to a folder where you don't have permissions. 在代码示例中,try ... catch构造用于在到达您没有权限的文件夹时停止搜索。

So based on this, my understanding of your question could be phrased as "How can I tell if I have permission to read a folder without trying to read the folder and throwing an exception if I don't have rights?" 因此,基于此,我对您的问题的理解可以表达为“如果我没有权限,我怎么能判断我是否有权读取文件夹而不尝试读取文件夹并抛出异常?”

If that's the case, then this related post will likely be helpful to you. 如果是这种情况,那么这篇相关文章可能会对您有所帮助。

Checking for directory and file write permissions in .NET 检查.NET中的目录和文件写入权限

Added 添加

I would agree with @jdehaan's answer, but only after reading the link I posted for the reason behind the recommendation. 我同意@jdehaan的回答,但只有在阅读了我发布的链接后才推荐。

What type of exception are you getting? 你得到什么类型的例外?

If you are getting a SecurityException you should have a look at this example on MSDN 如果您收到SecurityException,您应该在MSDN上查看此示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM