Removing an (apparently) infinitely recursive folder

Solution 1:

Thanks to everyone for the useful advice.

Straying well into StackOverflow territory, I've solved the problem by knocking up this snippet of C# code. It uses the Delimon.Win32.IO library that specifically addresses issues accessing long file paths.

Just in case this can help someone else out, here's the code - it got through the ~1600 levels of recursion I'd somehow been stuck with and took around 20 minutes to remove them all.

using System;
using Delimon.Win32.IO;

namespace ConsoleApplication1
{
    class Program
    {
        private static int level;
        static void Main(string[] args)
        {
            // Call the method to delete the directory structure
            RecursiveDelete(new DirectoryInfo(@"\\server\\c$\\storage\\folder1"));
        }

        // This deletes a particular folder, and recurses back to itself if it finds any subfolders
        public static void RecursiveDelete(DirectoryInfo Dir)
        {
            level++;
            Console.WriteLine("Now at level " +level);
            if (!Dir.Exists)
                return;

            // In any subdirectory ...
            foreach (var dir in Dir.GetDirectories())
            {
                // Call this method again, starting at the subdirectory
                RecursiveDelete(dir);
            }

            // Finally, delete the directory, and any files below it
            Dir.Delete(true);
            Console.WriteLine("Deleting directory at level " + level);
            level--;
        }
    }
}

Solution 2:

Could be a recursive junction point. Such a thing can be created with junction a file and disk utility from Sysinternals.

mkdir c:\Hello
junction c:\Hello\Hello c:\Hello

And you can now go endlessly down c:\Hello\Hello\Hello.... (well until MAX_PATH is reached, 260 characters for most commands but 32,767 characters for some Windows API functions).

A directory list shows that it is a junction:

C:\>dir c:\hello
 Volume in drive C is DR1
 Volume Serial Number is 993E-B99C

 Directory of c:\hello

12/02/2015  08:18 AM    <DIR>          .
12/02/2015  08:18 AM    <DIR>          ..
12/02/2015  08:18 AM    <JUNCTION>     hello [\??\c:\hello]
               0 File(s)              0 bytes
               3 Dir(s)  461,591,506,944 bytes free

C:\>

To delete use the junction utility:

junction -d c:\Hello\Hello

Solution 3:

Not an answer, but I don't have enough rep for a comment.

I once fixed this problem on a then-huge 500MB FAT16 disc on an MS-DOS system. I used DOS debug to manually dump and parse through the directory table. I then flipped one bit to mark the recursive directory as deleted. My copy of Dettman and Wyatt 'DOS Programmers' Reference' showed me the way.

I am still inordinately proud of this. I would be amazed and terrified if there is any general-purpose tool that has such power over FAT32 or NTFS volumes. Life was simpler back then.