C# 如何删除目录中的所有文件和文件夹?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1288718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete all files and folders in a directory?
提问by JL.
Using C#, how can I delete all files and folders from a directory, but still keep the root directory?
使用 C#,如何从目录中删除所有文件和文件夹,但仍保留根目录?
采纳答案by gsharp
System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
If your directory may have many files, EnumerateFiles()
is more efficient than GetFiles()
, because when you use EnumerateFiles()
you can start enumerating it before the whole collection is returned, as opposed to GetFiles()
where you need to load the entire collection in memory before begin to enumerate it. See this quote here:
如果您的目录可能有很多文件,EnumerateFiles()
则比 更有效GetFiles()
,因为当您使用时,EnumerateFiles()
您可以在返回整个集合之前开始枚举它,而不是GetFiles()
在开始枚举之前需要将整个集合加载到内存中。在这里看到这个报价:
Therefore, when you are working with many files and directories, EnumerateFiles() can be more efficient.
因此,当您处理许多文件和目录时,EnumerateFiles() 会更高效。
The same applies to EnumerateDirectories()
and GetDirectories()
. So the code would be:
这同样适用于EnumerateDirectories()
和GetDirectories()
。所以代码将是:
foreach (FileInfo file in di.EnumerateFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
dir.Delete(true);
}
For the purpose of this question, there is really no reason to use GetFiles()
and GetDirectories()
.
就这个问题而言,真的没有理由使用GetFiles()
and GetDirectories()
。
回答by Adam Robinson
Yes, that's the correct way to do it. If you're looking to give yourself a "Clean" (or, as I'd prefer to call it, "Empty" function), you can create an extension method.
是的,这是正确的做法。如果您想给自己一个“Clean”(或者,我更喜欢称之为“Empty”函数),您可以创建一个扩展方法。
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);
}
This will then allow you to do something like..
这将允许你做类似的事情..
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\...");
directory.Empty();
回答by hiteshbiblog
The following code will clear the folder recursively:
以下代码将递归清除文件夹:
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();
}
}
回答by zumalifeguard
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
}
}
If you know there are no sub-folders, something like this may be the easiest:
如果您知道没有子文件夹,这样的操作可能是最简单的:
Directory.GetFiles(folderName).ForEach(File.Delete)
回答by rasx
We can also show love for LINQ:
我们也可以表达对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));
Note that my solution here is not performant, because I am using Get*().ToList().ForEach(...)
which generates the same IEnumerable
twice. I use an extension method to avoid this issue:
请注意,我在这里的解决方案性能不佳,因为我正在使用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));
This is the extension method:
这是扩展方法:
/// <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);
}
}
}
回答by AVH
string directoryPath = "C:\Temp";
Directory.GetFiles(directoryPath).ToList().ForEach(File.Delete);
Directory.GetDirectories(directoryPath).ToList().ForEach(Directory.Delete);
回答by Thulasiram
new System.IO.DirectoryInfo(@"C:\Temp").Delete(true);
//Or
System.IO.Directory.Delete(@"C:\Temp", true);
回答by farfareast
In Windows 7, if you have just created it manually with Windows Explorer, the directory structure is similar to this one:
在 Windows 7 中,如果您刚刚使用 Windows 资源管理器手动创建它,则目录结构与此类似:
C:
\AAA
\BBB
\CCC
\DDD
And running the code suggested in the original question to clean the directory C:\AAA, the line di.Delete(true)
always fails with IOException "The directory is not empty" when trying to delete BBB. It is probably because of some kind of delays/caching in Windows Explorer.
并运行原始问题中建议的代码来清理目录 C:\AAA,di.Delete(true)
当尝试删除 BBB 时,该行总是以 IOException "The directory is not empty" 失败。这可能是因为 Windows 资源管理器中的某种延迟/缓存。
The following code works reliably for me:
以下代码对我来说可靠:
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);
}
}
回答by Alexandru Dicu
Every method that I tried, they have failed at some point with System.IO errors. The following method works for sure, even if the folder is empty or not, read-only or not, etc.
我尝试过的每种方法都在某些时候因 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);
回答by Manish Y
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);
}