How to handle UnauthorizedAccessException when attempting to add files from location without permissions

前端 未结 2 1851
清酒与你
清酒与你 2020-12-28 09:01

I am trying to get all files from folder this way:

try
{
    string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, \"*.*\", SearchOption.All         


        
2条回答
  •  梦谈多话
    2020-12-28 09:14

    see SafeFileEnumerator on this other post. I have used the SafeFileEnumerator code in the past with success. It prevents loosing the entire enumeration when you simply don't have access to a single file so you are still able to iterate through the files that you can access.

    EDIT: The version I have is slightly different from the one I linked to so let me share the version I have.

    public static class SafeFileEnumerator
    {
        public static IEnumerable EnumerateDirectories(string parentDirectory, string searchPattern, SearchOption searchOpt)
        {
            try
            {
                var directories = Enumerable.Empty();
                if (searchOpt == SearchOption.AllDirectories)
                {
                    directories = Directory.EnumerateDirectories(parentDirectory)
                        .SelectMany(x => EnumerateDirectories(x, searchPattern, searchOpt));
                }
                return directories.Concat(Directory.EnumerateDirectories(parentDirectory, searchPattern));
            }
            catch (UnauthorizedAccessException ex)
            {
                return Enumerable.Empty();
            }
        }
    
        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();
            }
        }
    }
    

    Example Usage:

    foreach(string fileName in SafeFileEnumerator.EnumerateFiles(folderPath, "*" + extension, SearchOption.AllDirectories))
    {
        //Do something with filename, store into an array or whatever you want to do.
    }
    

提交回复
热议问题