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


当前回答

System.IO.Directory.Delete(installPath, true);
System.IO.Directory.CreateDirectory(installPath);

其他回答

IO.Directory.Delete(HttpContext.Current.Server.MapPath(path), True)

你不需要更多

在我的情况下

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

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

删除所有可以删除的内容如果某些文件保留在文件夹中,则返回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;
    }
DirectoryInfo Folder = new DirectoryInfo(Server.MapPath(path)); 
if (Folder .Exists)
{
    foreach (FileInfo fl in Folder .GetFiles())
    {
        fl.Delete();
    }

    Folder .Delete();
}
System.IO.Directory.Delete(installPath, true);
System.IO.Directory.CreateDirectory(installPath);