Home
VB.NET
Sort by File Size
Updated Sep 25, 2022
Dot Net Perls
Sort files, size. Files have varying sizes. In VB.NET, we can use Directory.GetFiles and OrderByDescending along with the FileInfo type to sort them from largest to smallest.
With this function, we can determine the largest file in a directory. This may be the most important file. Alternatively, we can find the smallest file.
Example. We first invoke Directory.GetFiles, which returns a string array of the files in the directory. Next, we invoke the OrderByDescending method.
Array
Detail The OrderByDescending call is more complex. It receives a Func argument—this is an anonymous method.
Detail The Func method is created with anonymous method syntax. The Function receives a string (the file name) and returns its length.
So The OrderByDescending method sorts the files by their lengths. We then convert its result (an IEnumerable) into an array with ToArray.
ToArray
Imports System.IO Module Module1 Sub Main() ' The target directory. Dim dir As String = "C:\\programs" ' Get files. Dim files() As String = Directory.GetFiles(dir) ' Order files from largest size to smallest size. Dim sorted() As String = files.OrderByDescending( New Func(Of String, Integer)(Function(fn As String) Return New FileInfo(fn).Length End Function)).ToArray ' Loop and display files. For Each element As String In sorted Console.WriteLine(element) Console.WriteLine(New FileInfo(element).Length) Next End Sub End Module
C:\\programs\file.py 611 C:\\programs\file.rb 369 C:\\programs\file.php 235 C:\\programs\file.pl 184
In the output, we see that the folder contains four script files. The largest is file.py—it is 611 bytes. The smallest meanwhile is file.pl which is 184 bytes.
Tip This program is inefficient. If you built a data structure (a List of KeyValuePairs) you could avoid accessing FileInfo so many times.
List
KeyValuePair
Summary. This program uses System.IO functions to get a file array and their sizes. And with OrderByDescending we specify a lambda expression (an anonymous method) to sort the file names.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 25, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen