1

I have the following recursion code to get all the folders and files of a selected directory. But when I select a drive, for example E:\\ .., I am getting an error message of

"Access denied in accessing E:\system volume information"

Is it possible to bypass the system volume information folder?

This is the code I am using:

private static ArrayList GenerateFileList(string Dir)
{
    ArrayList fils = new ArrayList();
    bool Empty = true;

    foreach (string file in Directory.GetFiles(Dir)) // add each file in directory
    {
        fils.Add(file);
        Empty = false;
    }

    if (Empty)
    {
        if (Directory.GetDirectories(Dir).Length == 0)
            // if directory is completely empty, add it
        {
            fils.Add(Dir + @"/");
        }
    }

    foreach (string dirs in Directory.GetDirectories(Dir)) // recursive
    {
        foreach (object obj in GenerateFileList(dirs))
        {
            fils.Add(obj);
        }

    }
        return fils; // return file list
     }
munk
  • 12,340
  • 8
  • 51
  • 71
Mansi Rana
  • 11
  • 4
  • possible duplicate of [Ignore folders/files when Directory.GetFiles() is denied access](http://stackoverflow.com/questions/172544/ignore-folders-files-when-directory-getfiles-is-denied-access) – Hans Passant Mar 10 '14 at 22:00

1 Answers1

0
private static ArrayList GenerateFileList(string Dir)
{
    ArrayList fils = new ArrayList();
    bool Empty = true;

    try
    {
        foreach (string file in Directory.GetFiles(Dir)) // add each file in directory
        {
            fils.Add(file);
            Empty = false;
        }
    }
    catch(UnauthorizedAccessException e)
    {
        // I believe that's the right exception to catch - compare with what you get
        return new ArrayList();
    }

        if (Empty)
        {
            if (Directory.GetDirectories(Dir).Length == 0)
                // if directory is completely empty, add it
            {
                fils.Add(Dir + @"/");
            }
        }

    foreach (string dirs in Directory.GetDirectories(Dir)) // recursive
    {
        foreach (object obj in GenerateFileList(dirs))
        {
            fils.Add(obj);
        }
LB2
  • 4,802
  • 19
  • 35
  • hey thanks for your help please tell what reference should i use for AccessDeniedException – Mansi Rana Mar 10 '14 at 22:21
  • Looks like it should be [UnauthorizedAccessException](http://msdn.microsoft.com/en-us/library/system.unauthorizedaccessexception(v=vs.110).aspx) – LB2 Mar 10 '14 at 22:27