DirectoryInfo.Delete 与 Directory.Delete [英] DirectoryInfo.Delete vs Directory.Delete

查看:40
本文介绍了DirectoryInfo.Delete 与 Directory.Delete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除一些临时文件的内容,所以我正在开发为我删除它们的小程序.我有这两个代码示例,但我很困惑:

I want to delete the contents of some temp files so I am working on small program that deletes them for me. I have these two code samples but I'm confused as to:

  1. 哪个代码示例更好?
  2. 第一个示例 code1 删除文件 1 和 2,但第二个示例 code2 将删除文件夹 1 和 2 的包含?

代码1

    public void DeleteContains(string Pathz)
    {
        List<DirectoryInfo> FolderToClear = new List<DirectoryInfo>();
        FolderToClear.Add(new DirectoryInfo(@"C:UsersuserDesktop1"));
        FolderToClear.Add(new DirectoryInfo(@"C:UsersuserDesktop2"));

        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.

I believe the OP wants a comparison of DirectoryInfo.Delete and Directory.Delete.

如果您查看每个方法的反编译源代码(我使用 resharper 向我展示),您可以看到 DirectoryInfo.Delete 和 Directory.Delete 都使用 4 个参数调用 Delete 方法.恕我直言,唯一的区别是 Directory.Delete 必须调用 Path.GetFullPathInternal 来获取完整路径.Path.GetFullPathInternal 实际上是一个很长的方法,有很多检查.如果不进行一系列性能测试,就不太可能确定哪个更快,速度更快.

If you look at the decompiled source for each method (I used resharper to show me), you can see that DirectoryInfo.Delete and Directory.Delete both call the Delete method with 4 arguments. IMHO, the only difference is that Directory.Delete has to call Path.GetFullPathInternal to get the fullpath. Path.GetFullPathInternal is actually a very long method with lots of checks. Without doing a series of tests for performance, it would be unlikely to determine which is faster and by how much.

目录.删除

    [ResourceExposure(ResourceScope.Machine)]
    [ResourceConsumption(ResourceScope.Machine)]
    public static void Delete(String path, bool recursive)
    { 
        String fullPath = Path.GetFullPathInternal(path);
        Delete(fullPath, path, recursive, true); 
    } 

目录信息.删除

    [ResourceExposure(ResourceScope.None)] 
    [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
    public void Delete(bool recursive) 
    {
        Directory.Delete(FullPath, OriginalPath, recursive, true);
    }

这篇关于DirectoryInfo.Delete 与 Directory.Delete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆