Ignore folders/files when Directory.GetFiles() is denied access

前端 未结 8 1841
余生分开走
余生分开走 2020-11-22 04:27

I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method co

8条回答
  •  [愿得一人]
    2020-11-22 04:50

    I prefer using c# framework functions, but the function i need will be included in .net framework 5.0, so i have to write it.

    // search file in every subdirectory ignoring access errors
        static List list_files(string path)
        {
            List files = new List();
    
            // add the files in the current directory
            try
            {
                string[] entries = Directory.GetFiles(path);
    
                foreach (string entry in entries)
                    files.Add(System.IO.Path.Combine(path,entry));
            }
            catch 
            { 
            // an exception in directory.getfiles is not recoverable: the directory is not accessible
            }
    
            // follow the subdirectories
            try
            {
                string[] entries = Directory.GetDirectories(path);
    
                foreach (string entry in entries)
                {
                    string current_path = System.IO.Path.Combine(path, entry);
                    List files_in_subdir = list_files(current_path);
    
                    foreach (string current_file in files_in_subdir)
                        files.Add(current_file);
                }
            }
            catch
            {
                // an exception in directory.getdirectories is not recoverable: the directory is not accessible
            }
    
            return files;
        }
    

提交回复
热议问题