Быстрое получение всех файлов и каталогов по определенному пути

Я создаю приложение резервного копирования, в котором c # сканирует каталог. Прежде чем использовать что-то вроде этого, чтобы получить все файлы и субфайлы в каталоге:

DirectoryInfo di = new DirectoryInfo("A:\\");
var directories= di.GetFiles("*", SearchOption.AllDirectories);

foreach (FileInfo d in directories)
{
       //Add files to a list so that later they can be compared to see if each file
       // needs to be copid or not
}

Единственная проблема в том, что иногда к файлу не удается получить доступ, и я получаю несколько ошибок. Пример ошибки, которую я получаю: error

В результате я создал рекурсивный метод, который будет сканировать все файлы в текущем каталоге.Если в этом каталоге есть каталоги, метод будет вызываться снова, передавая этот каталог. В этом методе хорошо то, что я мог помещать файлы в блок try catch, давая мне возможность добавить эти файлы в список, если там нет ошибок, и добавить каталог в другой список, если у меня были ошибки.

try
{
    files = di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);               
}
catch
{
     //info of this folder was not able to get
     lstFilesErrors.Add(sDir(di));
     return;
}

Итак этот метод отлично работает, единственная проблема в том, что сканирование большого каталога занимает много времени. Как я мог ускорить этот процесс? Мой реальный метод - это на случай, если он вам понадобится.

private void startScan(DirectoryInfo di)
{
    //lstFilesErrors is a list of MyFile objects
    // I created that class because I wanted to store more specific information
    // about a file such as its comparePath name and other properties that I need 
    // in order to compare it with another list

    // lstFiles is a list of MyFile objects that store all the files
    // that are contained in path that I want to scan

    FileInfo[] files = null;
    DirectoryInfo[] directories = null;
    string searchPattern = "*.*";

    try
    {
        files = di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);               
    }
    catch
    {
        //info of this folder was not able to get
        lstFilesErrors.Add(sDir(di));
        return;
    }

    // if there are files in the directory then add those files to the list
    if (files != null)
    {
        foreach (FileInfo f in files)
        {
            lstFiles.Add(sFile(f));
        }
    }


    try
    {
        directories = di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
    }
    catch
    {
        lstFilesErrors.Add(sDir(di));
        return;
    }

    // if that directory has more directories then add them to the list then 
    // execute this function
    if (directories != null)
        foreach (DirectoryInfo d in directories)
        {
            FileInfo[] subFiles = null;
            DirectoryInfo[] subDir = null;

            bool isThereAnError = false;

            try
            {
                subFiles = d.GetFiles();
                subDir = d.GetDirectories();

            }
            catch
            {
                isThereAnError = true;                                                
            }

            if (isThereAnError)
                lstFilesErrors.Add(sDir(d));
            else
            {
                lstFiles.Add(sDir(d));
                startScan(d);
            }


        }

}

Возникает проблема, если я пытаюсь обработать исключение с помощью чего-то вроде:

DirectoryInfo di = new DirectoryInfo("A:\\");
FileInfo[] directories = null;
            try
            {
                directories = di.GetFiles("*", SearchOption.AllDirectories);

            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("There was an error with UnauthorizedAccessException");
            }
            catch
            {
                Console.WriteLine("There was antother error");
            }

В том, что если возникает исключение, я не получаю файлов.

67
задан Tono Nam 19 May 2011 в 16:59
поделиться