Recursive delete of files and directories in C#

前端 未结 5 1701
暗喜
暗喜 2020-12-18 20:55

How to delete a given directory recursively in C# ? A directory containing files.

Should the System.IO.Directory.Delete with the second parameter true

相关标签:
5条回答
  • 2020-12-18 21:05

    The only solution that worked for me if the subdirectories also contains files is by using a recursive function:

        public static void RecursiveDelete(DirectoryInfo baseDir)
        {
            if (!baseDir.Exists)
                return;
    
            foreach (var dir in baseDir.EnumerateDirectories())
            {
                RecursiveDelete(dir);
            }
            baseDir.Delete(true);
        }
    

    It appears that Directory.Delete(dir, true) only delete files of the current directory, and subdirectories if they are empty.

    Hope it helps someone.

    btw, example: RecursiveDelete( new DirectoryInfo(@"C:\my_dir") );

    0 讨论(0)
  • 2020-12-18 21:19

    Yup, that's the point of that parameter. Did you try it and have any problems? (I've just double-checked, and it works fine for me.)

    0 讨论(0)
  • 2020-12-18 21:19

    Recursive works for both files and folders (oddly, I thought it didn't work for files; my bad...):

    // create some nested folders...
    Directory.CreateDirectory(@"c:\foo");
    Directory.CreateDirectory(@"c:\foo\bar");
    // ...with files...
    File.WriteAllText(@"c:\foo\blap.txt", "blup");
    File.WriteAllText(@"c:\foo\bar\blip.txt", "blop");
    // ...and delete them
    Directory.Delete(@"c:\foo", true); // fine
    
    0 讨论(0)
  • 2020-12-18 21:25

    Why do not use?

    Directory.Delete(directoryPath, true);

    https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx

    0 讨论(0)
  • 2020-12-18 21:28

    If you get UnauthorizedAccessException . You can use modified of RecursiveDelete from Jone Polvora. Thank you for Idea. I will use it.

        public static void RecursiveDelete(DirectoryInfo baseDir)
        {
            if (!baseDir.Exists)
                return;
    
            foreach (var dir in baseDir.EnumerateDirectories())
            {
                RecursiveDelete(dir);
            }
            var files = baseDir.GetFiles();
            foreach (var file in files)
            {
                file.IsReadOnly = false;
                file.Delete();
            }
            baseDir.Delete();
        }
    
    0 讨论(0)
提交回复
热议问题