使用C#,如何删除目录中的所有文件和文件夹,但仍然保留根目录?


当前回答

唯一应该做的就是将可选递归参数设置为True。

Directory.Delete(“C:\MyDummyDirectory”,True)

感谢.NET。:)

其他回答

我用过

Directory.GetFiles(picturePath).ToList().ForEach(File.Delete);

删除旧图片,我不需要此文件夹中的任何对象

在Windows 7中,如果您刚刚使用Windows资源管理器手动创建了它,则目录结构与以下类似:

C:
  \AAA
    \BBB
      \CCC
        \DDD

运行原始问题中建议的代码来清理目录C:\AAA,当尝试删除BBB时,行di.Delete(true)总是失败,并出现IOException“目录不是空的”。这可能是由于Windows资源管理器中的某种延迟/缓存。

以下代码对我来说工作可靠:

static void Main(string[] args)
{
    DirectoryInfo di = new DirectoryInfo(@"c:\aaa");
    CleanDirectory(di);
}

private static void CleanDirectory(DirectoryInfo di)
{
    if (di == null)
        return;

    foreach (FileSystemInfo fsEntry in di.GetFileSystemInfos())
    {
        CleanDirectory(fsEntry as DirectoryInfo);
        fsEntry.Delete();
    }
    WaitForDirectoryToBecomeEmpty(di);
}

private static void WaitForDirectoryToBecomeEmpty(DirectoryInfo di)
{
    for (int i = 0; i < 5; i++)
    {
        if (di.GetFileSystemInfos().Length == 0)
            return;
        Console.WriteLine(di.FullName + i);
        Thread.Sleep(50 * i);
    }
}

这是我看完所有帖子后使用的工具。确实如此

删除所有可以删除的内容如果某些文件保留在文件夹中,则返回false

它处理的是

只读文件删除延迟锁定的文件

它不使用Directory.Delete,因为该进程因异常而中止。

    /// <summary>
    /// Attempt to empty the folder. Return false if it fails (locked files...).
    /// </summary>
    /// <param name="pathName"></param>
    /// <returns>true on success</returns>
    public static bool EmptyFolder(string pathName)
    {
        bool errors = false;
        DirectoryInfo dir = new DirectoryInfo(pathName);

        foreach (FileInfo fi in dir.EnumerateFiles())
        {
            try
            {
                fi.IsReadOnly = false;
                fi.Delete();

                //Wait for the item to disapear (avoid 'dir not empty' error).
                while (fi.Exists)
                {
                    System.Threading.Thread.Sleep(10);
                    fi.Refresh();
                }
            }
            catch (IOException e)
            {
                Debug.WriteLine(e.Message);
                errors = true;
            }
        }

        foreach (DirectoryInfo di in dir.EnumerateDirectories())
        {
            try
            {
                EmptyFolder(di.FullName);
                di.Delete();

                //Wait for the item to disapear (avoid 'dir not empty' error).
                while (di.Exists)
                {
                    System.Threading.Thread.Sleep(10);
                    di.Refresh();
                }
            }
            catch (IOException e)
            {
                Debug.WriteLine(e.Message);
                errors = true;
            }
        }

        return !errors;
    }

在我的情况下

var PhotoFile = _context.Records.Where(x => id_or_ids.Contains(x.Id)).Select(x => x.Photo).ToList();

            System.IO.DirectoryInfo di = new DirectoryInfo("wwwroot/uploads");

            foreach (FileInfo file in di.GetFiles())
            {
                if (PhotoFile.IndexOf(file.Name) != -1)
                {
                    file.Delete();
                }
            }
IO.Directory.Delete(HttpContext.Current.Server.MapPath(path), True)

你不需要更多