skip目录没有必要的权限c#

时间:2015-03-17 06:49:38

标签: .net c#-4.0 directory

        private int GetFileCount(DirectoryInfo directory)
        {
            int retVal = directory.GetFiles().Length;

            try
            {
                Array.ForEach(directory.GetDirectories(), dir =>
                    {
                        retVal += GetFileCount(dir);
                    });
            }
            catch (UnauthorizedAccessException ex)
            {                
                //Here stops the execution
            }

            return retVal;
        }

当我扫描任何磁盘驱动器时,我写了上面的代码...给我访问拒绝异常..处理异常写入的catch块但是它会停止进一步的迭代......如何继续进一步迭代

1 个答案:

答案 0 :(得分:1)

在catch块内,请检查retval是否为null,如果是,则使用continue关键字和增量计数器值。这是一个示例:

private int GetFileCount( )
    { 
            string[] subdirectories = Directory.GetDirectories(@"C:\");
            string[] result = null;

            if (subdirectories.Length > 0)
            {
                for (int i = 0; i < subdirectories.Length - 1; i++)
                {
                    try
                    {
                        result = Directory.GetFiles(subdirectories[i]);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        if (result == null)
                        {
                            i += 1;
                            continue;
                        }
                    }
                }
            }          

        return 1;
    }