使用C#,如何从目录中删除所有文件和文件夹,但仍保留根目录?
29个解决方案
657 votes
System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
如果您的目录可能包含许多文件,则GetFiles()
比GetDirectories()
更有效,因为当您使用EnumerateFiles()
时,您可以在返回整个集合之前开始枚举它,而不是GetFiles()
,您需要在开始枚举之前将整个集合加载到内存中 它。 在这里看到这个引用:
因此,当您使用许多文件和目录时,EnumerateFiles()可以更有效。
这同样适用于GetFiles()
和GetDirectories()
.因此代码将是:
foreach (FileInfo file in di.EnumerateFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
dir.Delete(true);
}
出于这个问题的目的,没有理由使用GetFiles()
和GetDirectories()
。
gsharp answered 2018-12-26T10:24:56Z
162 votes
是的,这是正确的方法。 如果你想给自己一个“干净”(或者,我更喜欢称之为“清空”功能),你可以创建一个扩展方法。
public static void Empty(this System.IO.DirectoryInfo directory)
{
foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}
这将允许你做类似的事情..
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\...");
directory.Empty();
Adam Robinson answered 2018-12-26T10:25:20Z
64 votes
以下代码将递归清除该文件夹:
private void clearFolder(string FolderName)
{
DirectoryInfo dir = new DirectoryInfo(FolderName);
foreach(FileInfo fi in dir.GetFiles())
{
fi.Delete();
}
foreach (DirectoryInfo di in dir.GetDirectories())
{
clearFolder(di.FullName);
di.Delete();
}
}
hiteshbiblog answered 2018-12-26T10:25:41Z
37 votes
new System.IO.DirectoryInfo(@"C:\Temp").Delete(true);
//Or
System.IO.Directory.Delete(@"C:\Temp", true);
Thulasiram answered 2018-12-26T10:25:56Z
36 votes
我们也可以表达对LINQ的热爱:
using System.IO;
using System.Linq;
…
var directory = Directory.GetParent(TestContext.TestDir);
directory.EnumerateFiles()
.ToList().ForEach(f => f.Delete());
directory.EnumerateDirectories()
.ToList().ForEach(d => d.Delete(true));
请注意,我的解决方案不符合要求,因为我使用的是Get*().ToList().ForEach(...)
两次生成相同的IEnumerable
。 我使用扩展方法来避免此问题:
using System.IO;
using System.Linq;
…
var directory = Directory.GetParent(TestContext.TestDir);
directory.EnumerateFiles()
.ForEachInEnumerable(f => f.Delete());
directory.EnumerateDirectories()
.ForEachInEnumerable(d => d.Delete(true));
这是扩展方法:
/// <summary>
/// Extensions for <see cref="System.Collections.Generic.IEnumerable"/>.
/// </summary>
public static class IEnumerableOfTExtensions
{
/// <summary>
/// Performs the <see cref="System.Action"/>
/// on each item in the enumerable object.
/// </summary>
/// <typeparam name="TEnumerable">The type of the enumerable.</typeparam>
/// <param name="enumerable">The enumerable.</param>
/// <param name="action">The action.</param>
/// <remarks>
/// “I am philosophically opposed to providing such a method, for two reasons.
/// …The first reason is that doing so violates the functional programming principles
/// that all the other sequence operators are based upon. Clearly the sole purpose of a call
/// to this method is to cause side effects.”
/// —Eric Lippert, “foreach” vs “ForEach” [http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx]
/// </remarks>
public static void ForEachInEnumerable<TEnumerable>(this IEnumerable<TEnumerable> enumerable, Action<TEnumerable> action)
{
foreach (var item in enumerable)
{
action(item);
}
}
}
rasx answered 2018-12-26T10:26:25Z
29 votes
最简单的方法:
Directory.Delete(path,true);
Directory.CreateDirectory(path);
请注意,这可能会删除该文件夹的某些权限。
Igor Mukhachev answered 2018-12-26T10:26:51Z
24 votes
基于hiteshbiblog,您可能应该确保该文件是可读写的。
private void ClearFolder(string FolderName)
{
DirectoryInfo dir = new DirectoryInfo(FolderName);
foreach (FileInfo fi in dir.GetFiles())
{
fi.IsReadOnly = false;
fi.Delete();
}
foreach (DirectoryInfo di in dir.GetDirectories())
{
ClearFolder(di.FullName);
di.Delete();
}
}
如果您知道没有子文件夹,这样的事情可能是最简单的:
Directory.GetFiles(folderName).ForEach(File.Delete)
zumalifeguard answered 2018-12-26T10:27:16Z
12 votes
System.IO.Directory.Delete(installPath, true);
System.IO.Directory.CreateDirectory(installPath);
MacGyver answered 2018-12-26T10:27:33Z
6 votes
我尝试过的每一种方法,在某些方面都出现了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);
Alexandru Dicu answered 2018-12-26T10:27:56Z
6 votes
以下代码将清除目录,但保留根目录(递归)。
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);
hofi answered 2018-12-26T10:28:16Z
4 votes
仅使用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);
}
}
Kriil answered 2018-12-26T10:28:45Z
3 votes
在Windows 7中,如果您刚刚使用Windows资源管理器手动创建它,则目录结构与此类似:
C:
\AAA
\BBB
\CCC
\DDD
并且运行原始问题中建议的代码来清理目录C:\ AAA,第di.Delete(true)
行在尝试删除BBB时始终因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);
}
}
farfareast answered 2018-12-26T10:29:24Z
3 votes
private void ClearFolder(string FolderName)
{
DirectoryInfo dir = new DirectoryInfo(FolderName);
foreach (FileInfo fi in dir.GetFiles())
{
fi.IsReadOnly = false;
fi.Delete();
}
foreach (DirectoryInfo di in dir.GetDirectories())
{
ClearFolder(di.FullName);
di.Delete();
}
}
Mong Zhu answered 2018-12-26T10:29:41Z
2 votes
string directoryPath = "C:\Temp";
Directory.GetFiles(directoryPath).ToList().ForEach(File.Delete);
Directory.GetDirectories(directoryPath).ToList().ForEach(Directory.Delete);
AVH answered 2018-12-26T10:29:57Z
2 votes
此版本不使用递归调用,并解决了readonly问题。
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();
}
}
Jeppe Andreasen answered 2018-12-26T10:30:37Z
2 votes
这是我阅读所有帖子后结束的工具。确实如此
- 删除所有可删除的内容
- 如果某些文件仍在文件夹中,则返回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;
}
Eric Bole-Feysot answered 2018-12-26T10:31:29Z
1 votes
使用DirectoryInfo的GetDirectories方法。
foreach (DirectoryInfo subDir in new DirectoryInfo(targetDir).GetDirectories())
subDir.Delete(true);
Mr_Hmp answered 2018-12-26T10:31:49Z
1 votes
以下示例显示了如何执行此操作。 它首先创建一些目录和一个文件,然后通过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。]
Salma Tofaily answered 2018-12-26T10:32:14Z
1 votes
这不是处理上述问题的最佳方式。 但它是另一种......
while (Directory.GetDirectories(dirpath).Length > 0)
{
//Delete all files in directory
while (Directory.GetFiles(Directory.GetDirectories(dirpath)[0]).Length > 0)
{
File.Delete(Directory.GetFiles(dirpath)[0]);
}
Directory.Delete(Directory.GetDirectories(dirpath)[0]);
}
dsmyrnaios answered 2018-12-26T10:32:44Z
0 votes
DirectoryInfo Folder = new DirectoryInfo(Server.MapPath(path));
if (Folder .Exists)
{
foreach (FileInfo fl in Folder .GetFiles())
{
fl.Delete();
}
Folder .Delete();
}
Ashok Luhach answered 2018-12-26T10:33:01Z
0 votes
using System;
using System.IO;
namespace DeleteFoldersAndFilesInDirectory
{
class Program
{
public static void DeleteAll(string path)
{
string[] directories = Directory.GetDirectories(path);
string[] files = Directory.GetFiles(path);
foreach (string x in directories)
Directory.Delete(x, true);
foreach (string x in files)
File.Delete(x);
}
static void Main()
{
Console.WriteLine("Enter The Directory:");
string directory = Console.ReadLine();
Console.WriteLine("Deleting all files and directories ...");
DeleteAll(directory);
Console.WriteLine("Deleted");
}
}
}
Diaa Eddin answered 2018-12-26T10:33:17Z
0 votes
这将显示我们如何删除文件夹并检查它我们使用文本框
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();
}
}
}
Abdelrhman Khalil answered 2018-12-26T10:34:11Z
0 votes
using System.IO;
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);
SynsMasTer answered 2018-12-26T10:34:26Z
0 votes
从主要电话
static void Main(string[] args)
{
string Filepathe =<Your path>
DeleteDirectory(System.IO.Directory.GetParent(Filepathe).FullName);
}
添加此方法
public static void DeleteDirectory(string path)
{
if (Directory.Exists(path))
{
//Delete all files from the Directory
foreach (string file in Directory.GetFiles(path))
{
File.Delete(file);
}
//Delete all child Directories
foreach (string directory in Directory.GetDirectories(path))
{
DeleteDirectory(directory);
}
//Delete a Directory
Directory.Delete(path);
}
}
sansalk answered 2018-12-26T10:34:51Z
0 votes
foreach (string file in System.IO.Directory.GetFiles(path))
{
System.IO.File.Delete(file);
}
foreach (string subDirectory in System.IO.Directory.GetDirectories(path))
{
System.IO.Directory.Delete(subDirectory,true);
}
Manish Y answered 2018-12-26T10:35:06Z
0 votes
要删除文件夹,这是使用文本框和按钮using System.IO;
的代码:
private void Deletebt_Click(object sender, EventArgs e)
{
System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(@"" + delete.Text);
foreach (FileInfo file in myDirInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
dir.Delete(true);
}
}
Abdelrhman Khalil answered 2018-12-26T10:35:26Z
-2 votes
private void ClearDirectory(string path)
{
if (Directory.Exists(path))//if folder exists
{
Directory.Delete(path, true);//recursive delete (all subdirs, files)
}
Directory.CreateDirectory(path);//creates empty directory
}
dadziu answered 2018-12-26T10:35:42Z
-3 votes
您应该做的唯一事情是将Directory.Delete("C:\MyDummyDirectory", True)
设置为True
。
Directory.Delete("C:\MyDummyDirectory", True)
感谢.NET。:)
LysanderM answered 2018-12-26T10:36:10Z
-4 votes
IO.Directory.Delete(HttpContext.Current.Server.MapPath(path), True)
你不需要更多