Desktop Functions:

   Smart Device Functions:

Show Recent Changes
Subscribe (RSS)
Misc. Pages
Helpful Tools
Suggested Reading
Website TODO List
Support Forum
Download Visual Studio Add-In

Terms of Use
Privacy Policy
removedirectory (kernel32)

C# Signature:

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

User-Defined Types:



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 ( 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;
        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)

Sample Code:

  String path = @"c:\temp\oldDir";

Alternative Managed API:



Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

Access directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version