I have been trying to look for a file in all the possible directories inside "My Documents", but it's throwing the "System.UnauthorizedAccessException" exception because of the "My music" folder.
I thought maybe listing all the folders within "My documents", then getting the path of "My music" and excluding it from being searched would solve the problem, but it failed...
So now I have no idea how to find a specific ".ini" file within all the folders inside "My documents" without getting that exception, can anyone help me please? :)
The code I used:
DirectoryInfo dir = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
foreach(FileInfo file in dir.GetFiles("*.ini", SearchOption.AllDirectories))
{
listBox1.Items.Add(file.Name);
}
There are many issues to deal with other than your current
System.UnauthorizedAccessException
such as "reparse points" (hard links, junction points, symbolic links, etc).You really should read this article before going ANY further:
Folder Recursion
It doesn't cover all of the issues that come to my mind, but the solution given in the article is a very good step in the right direction to avoid a lot of 'unknowns'.
Edit://
I mention reparse points because these are used (AFAIK) in Windows 7, 8?, etc to constitute the
SpecialFolder
objects.For example:
"C:\Users\UserName\My Documents"
is a NTFS junction which points to"C:\Users\UserName\Documents"
.I feel it is important to point this out because there is no explicit rule which would prevent me from setting the ACL on
"C:\Users\UserName\My Documents"
to disallow anyone but, say, Administrators from accessing"C:\Users\UserName\Documents"
via the junction/ symbolic link, thus sending you down yet another rabbit hole :-)