3

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

  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:\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);
        }
    }
4

2 回答 2

2

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

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.

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);
    }
于 2012-12-14T19:24:12.210 回答
0

第一个代码示例将只删除文件夹“C:\Users\user\Desktop\1”和“C:\Users\user\Desktop\2”,而不管参数中传递了什么。

第二个代码示例将删除参数指定的目录内的所有文件和文件夹。

于 2012-12-14T19:10:02.913 回答