使用C#,如何删除目录中的所有文件和文件夹,但仍然保留根目录?
当前回答
using System.IO;
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);
其他回答
下面的示例显示了如何做到这一点。它首先创建一些目录和文件,然后通过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。
在我的情况下
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();
}
}
仅对File和Directory而不是FileInfo和DirectoryInfo使用静态方法将执行速度更快。(请参阅C#中File和FileInfo之间的区别是什么?)。答案显示为实用方法。
public static void Empty(string directory)
{
foreach(string fileToDelete in System.IO.Directory.GetFiles(directory))
{
System.IO.File.Delete(fileToDelete);
}
foreach(string subDirectoryToDeleteToDelete in System.IO.Directory.GetDirectories(directory))
{
System.IO.Directory.Delete(subDirectoryToDeleteToDelete, true);
}
}
DirectoryInfo Folder = new DirectoryInfo(Server.MapPath(path));
if (Folder .Exists)
{
foreach (FileInfo fl in Folder .GetFiles())
{
fl.Delete();
}
Folder .Delete();
}
System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
如果您的目录可能有许多文件,EnumerateFiles()比GetFiles()更有效,因为当您使用EnumerateFile()时,您可以在返回整个集合之前开始枚举它,而不是GetFiles(,在开始枚举之前,您需要在内存中加载整个集合。请参阅此处的引用:
因此,当您使用许多文件和目录时,EnumerateFiles()可以更有效。
这同样适用于EnumerateDirectories()和GetDirectory()。所以代码应该是:
foreach (FileInfo file in di.EnumerateFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
dir.Delete(true);
}
对于这个问题,确实没有理由使用GetFiles()和GetDirectories()。