使用C#,如何删除目录中的所有文件和文件夹,但仍然保留根目录?
当前回答
下面的示例显示了如何做到这一点。它首先创建一些目录和文件,然后通过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();
}
}
private void ClearFolder(string FolderName)
{
DirectoryInfo dir = new DirectoryInfo(FolderName);
foreach(FileInfo fi in dir.GetFiles())
{
try
{
fi.Delete();
}
catch(Exception) { } // Ignore all exceptions
}
foreach(DirectoryInfo di in dir.GetDirectories())
{
ClearFolder(di.FullName);
try
{
di.Delete();
}
catch(Exception) { } // Ignore all exceptions
}
}
如果您知道没有子文件夹,那么像这样的操作可能是最简单的:
Array.ForEach(Directory.GetFiles(folderName), File.Delete);
最简单的方法:
Directory.Delete(path,true);
Directory.CreateDirectory(path);
请注意,这可能会删除文件夹上的某些权限。
在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);
}
}
这将显示我们如何删除文件夹并使用文本框进行检查
using System.IO;
namespace delete_the_folder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Deletebt_Click(object sender, EventArgs e)
{
//the first you should write the folder place
if (Pathfolder.Text=="")
{
MessageBox.Show("ples write the path of the folder");
Pathfolder.Select();
//return;
}
FileAttributes attr = File.GetAttributes(@Pathfolder.Text);
if (attr.HasFlag(FileAttributes.Directory))
MessageBox.Show("Its a directory");
else
MessageBox.Show("Its a file");
string path = Pathfolder.Text;
FileInfo myfileinf = new FileInfo(path);
myfileinf.Delete();
}
}
}