Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
958 views
in Technique[技术] by (71.8m points)

c# - DirectoryInfo.Delete vs 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. Which code sample is better?
  2. The first sample, code1, deletes the files 1 and 2 but the second sample, code2 will delete the contains of folder 1 and 2?

code1

    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);
        }
    }

code 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);
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...