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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With