Josh Cox

Apr 2018

A Problematic Place

by in CodeSOD on

In programming, sometimes the ordering of your data matters. And sometimes the ordering doesn’t matter and it can be completely random. And sometimes… well, El Dorko found a case where it apparently matters that it doesn’t matter:

DirectoryInfo di = new DirectoryInfo(directory);
FileInfo[] files = di.GetFiles();
DirectoryInfo[] subdirs = di.GetDirectories();

// shuffle subdirs to avoid problematic places
Random rnd = new Random();
for( int i = subdirs.Length - 1; i > 0; i-- )
{
    int n = rnd.Next( i + 1 );
    DirectoryInfo tmp = subdirs[i];
    subdirs[i] = subdirs[n];
    subdirs[n] = tmp;
}

foreach (DirectoryInfo dir in subdirs)
{
   // process files in directory
}