Optimised Directory Scanning in C# 

 

Sat, 20 Sep 2008 21:13:56 GMT

I'm working on a new application to manage ID3 tags in my huge MP3 database.  Besides the actual ID3 editing, I need to make sure the scanner runs as fast as possible.  I'm testing some methods below and I'll post results later!

static public string[] GetAllFileNames(string baseDir)
    {
        // Store results in the file results list.
        List<string> fileResults = new List<string>();

        // Store a stack of our directories.
        Stack<string> directoryStack = new Stack<string>();
        directoryStack.Push(baseDir);

        // While there are directories to process and we don't have too many results
        while (directoryStack.Count > 0 && fileResults.Count < 1000)
        {
            string currentDir = directoryStack.Pop();

            // Add all files at this directory.
            foreach (string fileName in Directory.GetFiles(currentDir, "*.*"))
            {
                fileResults.Add(fileName);
            }

            // Add all directories at this directory.
            foreach (string directoryName in Directory.GetDirectories(currentDir))
            {
                directoryStack.Push(directoryName);
            }
        }
        return fileResults.ToArray();
    }


Comments: No Comments

Leave a Comment

Comments (required)