0

I'm creating a method to handle file exceptions.

I have listed all files in a directory and search for subdirectories and list all files in those subdirectories too on the C:\Users\ folder

listBox1.Items.AddRange(Directory.GetFiles("C:\\Users\\", "*", SearchOption.AllDirectories));

Some files are protected by windows, and when you run a command for those files it gives me an exception.

If there is any possible, How can I save the files that returned the exception to another listbox when the exception happens and continue listing the files to first listbox?

I love Code
  • 101
  • 1
  • 7
  • 1
    Is `listbox` a `.NET` component ? Or a `Windows.Forms` one? Also, you can `try/catch` to do such a treatment. – Eric Wu Jul 31 '17 at 12:47
  • Check this answer, you may need to do the traversal manually https://stackoverflow.com/a/172575/920557. – Eugene Komisarenko Jul 31 '17 at 12:50
  • I would have try / catch the exception and see what info of the file i have in the exception to file my second list. – JBO Jul 31 '17 at 12:51

1 Answers1

0

try this:

 private List<string> GetFiles(string path, string pattern)
    {
        var files = new List<string>();

        try
        {
            files.AddRange(Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly));
            foreach (var directory in Directory.GetDirectories(path))
                files.AddRange(GetFiles(directory, pattern));
        }
        catch (UnauthorizedAccessException ex)
        {
            // unnautorized files, create another list and add here.
        }

        return files;

    }
Thiago Loureiro
  • 1,041
  • 13
  • 24