views:

340

answers:

3

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?

+8  A: 

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.

jdehaan
+1 - good answer.
David Stratton
Catching execption in recursive function can cause poor performance, can you perform a check to see whether a directory is accessible first
Rohan West
@Rohan, checking access to directory will require more code and overhead on cpu rather then trying to access directly and let exception fire, the reason is, the ACL is native win32 code, so when you try to check access to directory, you will indeed spend more time on marshelling data between win32 and CLR objects. It will not put any performance overhead against checking access.
Akash Kava
+3  A: 

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.

http://stackoverflow.com/questions/1281620/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.

David Stratton
A: 

What type of exception are you getting?

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

Rohan West
UnauthorisedAccessException