TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Sort by File Size

Sort files by their sizes in bytes using the System.Linq namespace.
Sort files, size. Each file in a directory has a size in bytes. We use a C# method to sort an array of these files by their sizes in bytes. This is sometimes useful for categorization and presenting UIs with file lists.Sort
Example. We sort files using the LINQ extension methods. We use the FileInfo class and its Length property to get the length of each file. The File class doesn't have a Length getter, and reading in the entire file each time would be wasteful.

GetFiles: The program uses the Directory.GetFiles method found in the System.IO namespace.

File

Tip: This is the easiest and normally the best way to get a string array containing each file name.

Array: The identifier "fns" is used to reference the string array. An English word would be better style.

Array
C# program that sorts files by size using System; using System.IO; using System.Linq; class Program { static void Main() { // Directory of files. const string dir = "C:\\site"; // File names. string[] fns = Directory.GetFiles(dir); // Order by size. var sort = from fn in fns orderby new FileInfo(fn).Length descending select fn; // List files. foreach (string n in sort) { Console.WriteLine(n); } } } Output (List of all files in the directory)
Understanding query syntax. We use the special LINQ syntax to order the string array by each Length value from the FileInfo of each file. We can use any C# expression in the query orderby part. The program then lists the files.

Tip: The descending contextual keyword is used in this example and you can find more information on this useful keyword.

Descending
Summary. We sorted files by their sizes using the C# language and its LINQ extensions. In complex applications, you will store the file metadata in your object models. But not all applications are complex and this code is useful for small tasks.FileInfo
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf