RemoveDirectory (kernel32)
Last changed: ozbobwa-118.208.182.144

.
Summary

C# Signature:

[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
static extern bool RemoveDirectory(string lpPathName);

User-Defined Types:

None.

Notes:

Only deletes the end-most directory. The directory must be empty.

Tips & Tricks:

Iteratively Remove a Directory Tree

I updated the create directory code (LongPathDirectory.Delete()) code in the Microsoft.Experimental.IO project (http://bcl.codeplex.com/releases/view/42783) so some of the classes referenced in the code below are from that project.

    internal static class NativeMethods
    {
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool RemoveDirectory(string lpPathName);
    }

    public static void Delete(string path)
    {
        if (String.IsNullOrEmpty(path))
        {
        throw new ArgumentException("Path cannot be an empty string.");
        }

        char[] dirSeps = new char[] { '\\', '/' };

        string normalizedPath = LongPathCommon.NormalizeLongPath(path);

        // Get the minimum number of path separators in a valid string... will vary depending on whether it's a UNC path or not.
        int minDirSepPos = 4;   // \\?\c:\dir
        if (normalizedPath.Contains("UNC"))
        {
        minDirSepPos = 6;   // \\?\UNC\server\share\dir
        }

        // Get the minimum remaining string length once all required path components are accounted for.
        int minLength = -1;
        try
        {
        for (int i = 0; i < minDirSepPos; i++)
        {
            minLength = normalizedPath.IndexOfAny(dirSeps, ++minLength);
        }
        }
        catch (ArgumentOutOfRangeException e)
        {
        throw new ArgumentException("Invalid path specified: " + path);
        }

        while (true)
        {
        // Remove the path
        if (!NativeMethods.RemoveDirectory(normalizedPath))
        {
            throw LongPathCommon.GetExceptionFromLastWin32Error();
        }

        normalizedPath = normalizedPath.Remove(normalizedPath.LastIndexOfAny(dirSeps));

        if (normalizedPath.Length <= minLength)
        {
            break;
        }
        }
    }

Sample Code:

  String path = @"c:\temp\oldDir";
  RemoveDirectory(path);

Alternative Managed API:

System.IO.Directory.Delete().

Documentation