Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Biggest 10 files in a directory

Tags:

c#

filesystems

I need to get the largest 10 files in a directory. What I thought of doing is the following:

const noFiles = 10;
biggestFilesArray [noFiles][noFiles]; // file path and file size
const minLength = 0;
string [] fileEntries = Directory.GetFiles(path);
foreach (string _file in fileEntries)
{
// fill in first 10 files in the array then check if file size bigger than smallest inserted file. If yes then insert it and take smallest out.

}
// Sort Array 

Is there any built in method that can do this for me?

like image 919
RonaDona Avatar asked Feb 10 '14 02:02

RonaDona


1 Answers

You could get all the files in a directory, then take the 10 largest ones using LINQ.

The result will be a collection of FileInfo objects.

var di = new DirectoryInfo("someDirectory");

var result = di.GetFiles().OrderByDescending(x => x.Length).Take(10).ToList();

The DirectoryInfo and FileInfo classes provide much more info than the call to Directory.GetFiles(), which only returns a list of file names.


If all you needed in the end was the full file path/name (like GetFiles() returns):

var topTenNames
  = di.GetFiles().OrderByDescending(x => x.Length).Take(10).Select(x => x.FullName).ToList();

You posted in a comment that you're using Delimon.Win32.IO instead of System.IO, which has a newer version for .NET 4.0.

I downloaded and checked the source code. Unfortunately, search ing all directories was never implemented. They throw an exception with the same message on several other methods too.

public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption)
{
  if (searchOption == SearchOption.AllDirectories)
    throw new Exception("The method or operation is not implemented.");
  else
    return Helpers.FindDirectoriesInfos(this._sFullName, searchPattern);
}

I don't think I'd trust this assembly too much. Or I'd make really sure of what I was doing with it. Here's another method in their DirectoryInfo class. The System.IO version has a Delete method that accepts a bool indicating whether you'd like to delete subdirectories recursively. The default is false. In this class, it would appear you're being given the same choice, but internally there's a hard-coded true.

public bool Delete(bool recursive)
{
  return Helpers.DeleteDirectory(this._sFullName, true);
}
like image 60
Grant Winney Avatar answered Sep 29 '22 16:09

Grant Winney