什么是清空目录的最佳方式是什么? [英] What is the best way to empty a directory?
本文介绍了什么是清空目录的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法删除所有文件和放大器;子目录指定目录中没有迭代呢?
非优雅的解决方案:
公共静态无效EmptyDirectory(字符串路径)
{
如果(Directory.Exists(路径))
{
//删除所有文件
的foreach(在Directory.GetFiles var文件(路径))
{
File.Delete(文件);
}
//删除所有文件夹
的foreach(在Directory.GetDirectories var目录(路径))
{
Directory.Delete(目录,真正的);
}
}
}
解决方案
如何System.IO.Directory.Delete?它有一个递归选项,你甚至可以使用它。查看你的code,它看起来像你试图做一些事情略有不同 - 空目录而不删除它,对吗?嗯,你可以将其删除并重新创建它:)
在重新跨preting你的问题,这是最好的,我已经得到了:
的foreach(System.IO.FileSystemInfo FSI在
新System.IO.DirectoryInfo(路径).GetFileSystemInfos())
{
如果(FSI是System.IO.DirectoryInfo)
((System.IO.DirectoryInfo)FSI).Delete(真正的);
其他
fsi.Delete();
}
Is there a way to delete all files & sub-directories of a specified directory without iterating over them?
The non elegant solution:
public static void EmptyDirectory(string path)
{
if (Directory.Exists(path))
{
// Delete all files
foreach (var file in Directory.GetFiles(path))
{
File.Delete(file);
}
// Delete all folders
foreach (var directory in Directory.GetDirectories(path))
{
Directory.Delete(directory, true);
}
}
}
解决方案
How about System.IO.Directory.Delete? It has a recursion option, you're even using it. Reviewing your code it looks like you're trying to do something slightly different -- empty the directory without deleting it, right? Well, you could delete it and re-create it :)
After re-interpreting your question, this is the best I've got:
foreach(System.IO.FileSystemInfo fsi in
new System.IO.DirectoryInfo(path).GetFileSystemInfos())
{
if (fsi is System.IO.DirectoryInfo)
((System.IO.DirectoryInfo)fsi).Delete(true);
else
fsi.Delete();
}
这篇关于什么是清空目录的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文