Directory.EnumerateFiles => UnauthorizedAccessException

前端 未结 5 669
滥情空心
滥情空心 2020-11-27 03:42

There is a nice new method in .NET 4.0 for getting files in a directory in a streaming way via enumeration.

The problem here is that if one wishes to enumerate all f

5条回答
  •  伪装坚强ぢ
    2020-11-27 04:06

    I Couldn't get the above to work, but here is my implementation, i've tested it on c:\users on a "Win7" box, because if has all these "nasty" dirs:

    SafeWalk.EnumerateFiles(@"C:\users", "*.jpg", SearchOption.AllDirectories).Take(10)
    

    Class:

    public static class SafeWalk
    {
        public static IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOpt)
        {   
            try
            {
                var dirFiles = Enumerable.Empty();
                if(searchOpt == SearchOption.AllDirectories)
                {
                    dirFiles = Directory.EnumerateDirectories(path)
                                        .SelectMany(x => EnumerateFiles(x, searchPattern, searchOpt));
                }
                return dirFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
            }
            catch(UnauthorizedAccessException ex)
            {
                return Enumerable.Empty();
            }
        }
    }
    

提交回复
热议问题