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

前端 未结 2 1848
清酒与你
清酒与你 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:18

    You can use FileSystemInfo objects and recursion to accomplish this:

    static List files = new List();
    
    static void MyMethod() {
        DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
        ProcessFolder(dir.GetFileSystemInfos());
    }
    
    static void ProcessFolder(IEnumerable fsi) {
        foreach (FileSystemInfo info in fsi) {
    
            // We skip reparse points 
            if ((info.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) {
                Debug.WriteLine("Skipping reparse point '{0}'", info.FullName);
                return;
            }
    
            if ((info.Attributes & FileAttributes.Directory) == FileAttributes.Directory) {
                // If our FileSystemInfo object is a directory, we call this method again on the
                // new directory.
                try {
                    DirectoryInfo dirInfo = (DirectoryInfo)info;
                    ProcessFolder(dirInfo.GetFileSystemInfos());
                }
                catch (Exception ex) {
                    // Skipping any errors
                    // Really, we should catch each type of Exception - 
                    // this will catch -any- exception that occurs, 
                    // which may not be the behavior we want.
                    Debug.WriteLine("{0}", ex.Message);
                    break;
                }
            } else {
                // If our FileSystemInfo object isn't a directory, we cast it as a FileInfo object, 
                // make sure it's not null, and add it to the list.
                var file = info as FileInfo;
                if (file != null) {
                    files.Add(file.FullName);
                }
            }
        }
    }
    

    MyMethod takes your selected path and creates a DirectoryInfo object with it, and then calls the GetFileSystemInfos() method and passes that to the ProcessFolder method.

    The ProcessFolder method looks at each FileSystemInfo object, skips the reparse points, and if the FileSystemInfo object is a directory, calls the ProcessFolder method again - otherwise, it casts the FileSystemInfo object as a FileInfo object, makes sure it's not null, and then adds the filename to the list.

    More reading:

    • FileSystemInfo Class
    • DirectoryInfo Class
    • FileInfo Class

提交回复
热议问题