Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way of deleting files in a directory? (Except specific file extension)

I have seen questions like What is the best way to empty a directory?

But I need to know,

what is the fastest way of deleting all the files found within the directory, except any .zip files found.

Smells like linq here... or what?

By saying fastest way, I mean the Fastest execution time.

like image 227
GeorgeBoy Avatar asked Feb 12 '11 23:02

GeorgeBoy


People also ask

How do I Delete all files except a specific file extension?

Highlight all the files you want to keep by clicking the first file type, hold down the Shift key, and click the last file. Once all the files you want to keep are highlighted, on the Home Tab, click Invert Selection to select all other files and folders.

What is the fastest way to Delete files in a folder?

Open My Computer or Windows Explorer. Locate and select the file or folder you want to delete, click File in the top menu bar, and select Delete. If the File menu is not visible in My Computer or Windows Explorer, press the Alt key to make the menu bar visible, including the file menu.

How do you Delete all files with a specific extension in the working directory?

Using rm Command To remove a file with a particular extension, use the command 'rm'. This command is very easy to use, and its syntax is something like this.


4 Answers

If you are using .NET 4 you can benifit the smart way .NET now parallizing your functions. This code is the fasted way to do it. This scales with your numbers of cores on the processor too.

DirectoryInfo di = new DirectoryInfo(yourDir);
var files = di.GetFiles();

files.AsParallel().Where(f => f.Extension != ".zip").ForAll((f) => f.Delete());
like image 174
ceciliaSHARP Avatar answered Nov 15 '22 20:11

ceciliaSHARP


By fastest are you asking for the least lines of code or the quickest execution time? Here is a sample using LINQ with a parallel for each loop to delete them quickly.

string[] files = System.IO.Directory.GetFiles("c:\\temp", "*.*", IO.SearchOption.TopDirectoryOnly);

List<string> del = (
   from string s in files
   where ! (s.EndsWith(".zip"))
   select s).ToList();

Parallel.ForEach(del, (string s) => { IO.File.Delete(s); });
like image 26
Daniel Knoodle Avatar answered Nov 15 '22 21:11

Daniel Knoodle


At the time of writing this answer none of the previous answers used Directory.EnumerateFiles() which allows you to carry on operations on the list of files while the list is being constructed . Code:

Parallel.ForEach(Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).AsParallel(), Item =>
        {
            if(!string.Equals(Path.GetExtension(Item), ".zip",StringComparison.OrdinalIgnoreCase))
                File.Delete(Item);
        });

as far as I know the performance gain from using AsParallel() shouldn't be significant(if found) in this case however it did make difference in my case.

I compared the time it takes to delete all but .zip files in a list of 4689 files of which 10 were zip files using 1-foreach. 2-parallel foreach. 3-IEnumerable().AsParallel().ForAll. 4-parallel foreach using IEnumerable().AsParallel() as illustrated above. Results:

1-1545

2-1015

3-1103

4-839

the fifth and the last case was a normal foreach using Directory.GetFiles()

5-2266

of course the results weren't conclusive , as far as I know to carry on a proper benchmarking you need to use a ram drive instead of a HDD .

Note:that the performance difference between EnumerateFiles and GetFiles becomes more apparent as the number of files increases.

like image 42
ψευδή ηχώ Avatar answered Nov 15 '22 21:11

ψευδή ηχώ


Here's plain old C#

foreach(string file in Directory.GetFiles(Server.MapPath("~/yourdirectory")))
{
    if(Path.GetExtension(file) != ".zip")
    {
        File.Delete(file);
    }
}

And here's LINQ

var files = from f in Directory.GetFiles("")
            where Path.GetExtension(f) != ".zip"
            select f;

foreach(string file in files)
    File.Delete(file);
like image 45
Marko Avatar answered Nov 15 '22 22:11

Marko