DirectoryInfo.Delete与Directory.Delete
我想删除一些临时文件的内容,所以我正在处理为我删除它们的小程序。 我有这两个代码示例,但我很困惑:
- 哪个代码示例更好?
- 第一个示例code1删除文件1和2,但第二个示例,code2将删除文件夹1和2的包含?
代码1
public void DeleteContains(string Pathz) { List FolderToClear = new List(); 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); } }
编辑:我相信OP想要比较DirectoryInfo.Delete和Directory.Delete。
如果你查看每个方法的反编译源代码(我使用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); }
第一个代码示例将只删除文件夹“C:\ Users \ user \ Desktop \ 1”和“C:\ Users \ user \ Desktop \ 2”,无论参数中传递了什么。
第二个代码示例将删除参数指定的目录中的所有文件和文件夹。