I’ve got a Windows service installed as the local system account, and occasionally it builds a list of directories on the machine. It fails on Windows 7 under the c:\users… directories. I checked those folders out, and they appear to be under Full Control to the system account. Why would I be unable to access these directories?
System.UnauthorizedAccessException: Access to the path 'C:\Users\Public\Documents\My Videos' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, Boolean includeFiles, Boolean includeDirs, SearchOption searchOption)
at System.IO.Directory.GetDirectories(String path, String searchPattern, SearchOption searchOption)
at LS.Core.Backup.DirectoryMapper.GetDirectories(String SeedDir, Int32 Count)
Update:
See my answer below for details, but I’ve also posted the class I used to work around this issue. See GitHub Gist – DirectoryHelper
So I ended up answering this myself. The issue is with using
Directory.GetFiles()orDirectory.GetDirectories(). In Windows 7, using these methods, you will encounter junction points and/or hard links when searching beneath the C:\Users… tree because of the junction points added in for backwards compatibility with XP generation apps. MS fires an UnauthorizedAccessException when you try and read one of these junctions (to prevent possible infinite loops in the arrangement of those junctions), and it causes the entireGetFiles()orGetDirectories()call to fail, returning nothing. As a solution, I implemented a variant of http://tom-shelton.net/index.php/2010/01/02/using-extension-methods-and-the-win32-api-to-efficiently-enumerate-the-file-system/, which will iterate files one at a time, allowing you to handle the exception when you hit a junction and continue on. Pretty obtuse issue, hope it helps someone.