C# 递归搜索目录

发布于 2024-08-05 06:56:07 字数 144 浏览 1 评论 0原文

我需要在 C# 中递归遍历目录。我正在做类似这个的事情。但在遍历系统文件夹时它会抛出异常。如何在抛出异常之前检查它?

I need to recursively traverse directories in C#. I'm doing something like this. But it throws exception when iterating through system folders. How to check it before exception is thrown?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吝吻 2024-08-12 06:56:07

您必须检查访问权限,但我强烈建议捕获异常,这使代码更易于理解,并且还可以处理其他问题,例如当您想要远程解析目录并且网络出现故障时...

如果你为目录树制作一个 GUI,你还可以在你获得访问权限异常的地方添加一些漂亮的锁定图标,并在其他地方添加错误图标...在 C# 中,已经有一个很好的 免费开源组件 用于启动该组件。

如果您想计算文件和大小,则无法克服权限问题,您必须在更高权限的用户下运行您的工具。

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.

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.

游魂 2024-08-12 06:56:07

我看了你的链接和代码。在代码示例中,try...catch 构造用于在您到达没有权限的文件夹时停止搜索。

因此,基于此,我对您的问题的理解可以表述为“如何判断我是否有权读取文件夹,而无需尝试读取文件夹并在没有权限时抛出异常?”

如果是这样,那么这篇相关文章可能会对您有所帮助。

检查 .NET 中的目录和文件写入权限

已添加

我同意@jdehaan 的回答,但只有在阅读了我发布的推荐原因链接后才同意。

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.

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

Added

I would agree with @jdehaan's answer, but only after reading the link I posted for the reason behind the recommendation.

寻梦旅人 2024-08-12 06:56:07

您遇到什么类型的异常?

如果您收到 SecurityException,您应该在 MSDN

What type of exception are you getting?

If you are getting a SecurityException you should have a look at this example on MSDN

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文