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


当前回答

在我的情况下

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

其他回答

我尝试过的每一个方法都会在某个时候失败,并出现System.IO错误。即使文件夹为空或非空、只读或非只读等,以下方法也能正常工作。

ProcessStartInfo Info = new ProcessStartInfo();  
Info.Arguments = "/C rd /s /q \"C:\\MyFolder"";  
Info.WindowStyle = ProcessWindowStyle.Hidden;  
Info.CreateNoWindow = true;  
Info.FileName = "cmd.exe";  
Process.Start(Info); 

以下代码将清理目录,但将根目录保留在那里(递归)。

Action<string> DelPath = null;
DelPath = p =>
{
    Directory.EnumerateFiles(p).ToList().ForEach(File.Delete);
    Directory.EnumerateDirectories(p).ToList().ForEach(DelPath);
    Directory.EnumerateDirectories(p).ToList().ForEach(Directory.Delete);
};
DelPath(path);

下面的示例显示了如何做到这一点。它首先创建一些目录和文件,然后通过Directory.Delete(topPath,true);:

    static void Main(string[] args)
    {
        string topPath = @"C:\NewDirectory";
        string subPath = @"C:\NewDirectory\NewSubDirectory";

        try
        {
            Directory.CreateDirectory(subPath);

            using (StreamWriter writer = File.CreateText(subPath + @"\example.txt"))
            {
                writer.WriteLine("content added");
            }

            Directory.Delete(topPath, true);

            bool directoryExists = Directory.Exists(topPath);

            Console.WriteLine("top-level directory exists: " + directoryExists);
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.Message);
        }
    }

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

我知道这是一个古老的问题,但这是(也许是新的)正确答案:

new DirectoryInfo(folder).Delete(true);
Directory.CreateDirectory(folder);

删除所有递归,然后重新创建文件夹。

PS-必须具有使用System.IO的引用;

此版本不使用递归调用,并解决了只读问题。

public static void EmptyDirectory(string directory)
{
    // First delete all the files, making sure they are not readonly
    var stackA = new Stack<DirectoryInfo>();
    stackA.Push(new DirectoryInfo(directory));

    var stackB = new Stack<DirectoryInfo>();
    while (stackA.Any())
    {
        var dir = stackA.Pop();
        foreach (var file in dir.GetFiles())
        {
            file.IsReadOnly = false;
            file.Delete();
        }
        foreach (var subDir in dir.GetDirectories())
        {
            stackA.Push(subDir);
            stackB.Push(subDir);
        }
    }

    // Then delete the sub directories depth first
    while (stackB.Any())
    {
        stackB.Pop().Delete();
    }
}