我想删除一些临时文件的内容,所以我正在处理为我删除它们的小程序。我有这两个代码示例,但我很困惑:
CODE1
public void DeleteContains(string Pathz)
{
List<DirectoryInfo> FolderToClear = new List<DirectoryInfo>();
FolderToClear.Add(new DirectoryInfo(@"C:\Users\user\Desktop\1"));
FolderToClear.Add(new DirectoryInfo(@"C:\Users\user\Desktop\2"));
foreach (DirectoryInfo x in FolderToClear)
{
x.Delete(true);
}
}
代码2
private void DeleteContents(string Path)
{
string[] DirectoryList = Directory.GetDirectories(Path);
string[] FileList = Directory.GetFiles(Path);
foreach (string file in FileList)
{
File.Delete(file);
}
foreach ( string directoryin DirectoryList)
{
Directory.Delete(directory, true);
}
}
答案 0 :(得分:2)
如果你查看每个方法的反编译源代码(我使用resharper给我看),你可以看到DirectoryInfo.Delete和Directory.Delete都用4个参数调用Delete方法。恕我直言,唯一的区别是Directory.Delete必须调用Path.GetFullPathInternal来获取完整路径。 Path.GetFullPathInternal实际上是一个很长的方法,有很多检查。如果不对性能进行一系列测试,就不可能确定哪个更快,速度是多少。
Directory.Delete
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Delete(String path, bool recursive)
{
String fullPath = Path.GetFullPathInternal(path);
Delete(fullPath, path, recursive, true);
}
DirectoryInfo.Delete
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public void Delete(bool recursive)
{
Directory.Delete(FullPath, OriginalPath, recursive, true);
}
答案 1 :(得分:0)
第一个代码示例只会删除文件夹“C:\ Users \ user \ Desktop \ 1”和“C:\ Users \ user \ Desktop \ 2”,无论参数中传递了什么。
第二个代码示例将删除参数指定的目录中的所有文件和文件夹。