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?
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.
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.
What type of exception are you getting?
If you are getting a SecurityException you should have a look at this example on MSDN