C# Program to estimate the size of the file using LINQ

The Language Integrated Query (LINQ) in C# provides powerful methods to work with data from various sources, including files and directories. In this article, we'll explore how to estimate file sizes using LINQ operations, specifically calculating the average file size in a directory.

LINQ is part of the .NET framework that enables developers to write queries directly in C# using a SQL-like syntax. It provides a unified approach to query data from different sources like collections, databases, XML documents, and file systems.

Syntax

Following is the basic syntax for using LINQ to work with file information

var result = Directory.GetFiles("path")
                     .Select(file => new FileInfo(file).Length)
                     .Average();

The key components used in file size estimation

Directory.GetFiles("path")     // Gets all files in directory
.Select(file => ...)           // Projects each file to its length
new FileInfo(file).Length      // Gets file size in bytes
.Average()                     // Calculates average size

Key Methods and Classes

  • Directory.GetFiles() Returns an array of file names from the specified directory path.

  • Select() Projects each element of a sequence into a new form using a lambda expression.

  • FileInfo Provides properties and methods for file operations, including the Length property for file size.

  • Average() Computes the average of a sequence of numeric values.

  • Math.Round() Rounds a decimal value to a specified number of decimal places.

LINQ File Size Calculation Flow Directory GetFiles() File Array ["file1", "file2"] Select() FileInfo.Length Average() Final Result C:\MyFolder string[] file => file.Length double Each step transforms the data using LINQ operators

Using LINQ to Calculate Average File Size

Example

using System;
using System.Linq;
using System.IO;

class Program {
    static void Main(string[] args) {
        try {
            // Create a test directory with some files for demonstration
            string testDir = @"C:\TestFiles";
            Directory.CreateDirectory(testDir);
            
            // Create some test files with content
            File.WriteAllText(Path.Combine(testDir, "file1.txt"), "Hello World");
            File.WriteAllText(Path.Combine(testDir, "file2.txt"), "This is a test file with more content");
            File.WriteAllText(Path.Combine(testDir, "file3.txt"), "Small");
            
            // Get all files from the directory
            string[] files = Directory.GetFiles(testDir);
            
            // Calculate average file size using LINQ
            var avgSizeBytes = files.Select(file => new FileInfo(file).Length).Average();
            
            // Convert to KB and round to 2 decimal places
            var avgSizeKB = Math.Round(avgSizeBytes / 1024.0, 2);
            
            Console.WriteLine($"Directory: {testDir}");
            Console.WriteLine($"Number of files: {files.Length}");
            Console.WriteLine($"Average file size: {avgSizeKB} KB");
            
            // Clean up test files
            Directory.Delete(testDir, true);
        }
        catch (Exception ex) {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

The output of the above code is

Directory: C:\TestFiles
Number of files: 3
Average file size: 0.02 KB

Using LINQ with File Filtering

You can also filter files by extension or other criteria before calculating the average size

Example

using System;
using System.Linq;
using System.IO;

class Program {
    static void Main(string[] args) {
        try {
            // Create test directory and files
            string testDir = @"C:\TestFiles";
            Directory.CreateDirectory(testDir);
            
            File.WriteAllText(Path.Combine(testDir, "document.txt"), "Text file content");
            File.WriteAllText(Path.Combine(testDir, "data.csv"), "Name,Age\nJohn,25\nJane,30");
            File.WriteAllText(Path.Combine(testDir, "readme.md"), "# Markdown file");
            
            // Calculate average size for specific file types
            var txtFiles = Directory.GetFiles(testDir, "*.txt");
            var avgTxtSize = txtFiles.Select(file => new FileInfo(file).Length).Average();
            
            var allFiles = Directory.GetFiles(testDir);
            var avgAllSize = allFiles.Select(file => new FileInfo(file).Length).Average();
            
            Console.WriteLine($"Average .txt file size: {Math.Round(avgTxtSize, 1)} bytes");
            Console.WriteLine($"Average size of all files: {Math.Round(avgAllSize, 1)} bytes");
            
            // Show individual file sizes
            Console.WriteLine("\nIndividual file sizes:");
            foreach (var file in allFiles) {
                var fileInfo = new FileInfo(file);
                Console.WriteLine($"{Path.GetFileName(file)}: {fileInfo.Length} bytes");
            }
            
            Directory.Delete(testDir, true);
        }
        catch (Exception ex) {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

The output of the above code is

Average .txt file size: 17 bytes
Average size of all files: 19.7 bytes

Individual file sizes:
data.csv: 22 bytes
document.txt: 17 bytes
readme.md: 15 bytes

Advanced File Size Analysis

Example

using System;
using System.Linq;
using System.IO;

class Program {
    static void Main(string[] args) {
        try {
            string testDir = @"C:\TestFiles";
            Directory.CreateDirectory(testDir);
            
            // Create files of different sizes
            File.WriteAllText(Path.Combine(testDir, "small.txt"), "Hi");
            File.WriteAllText(Path.Combine(testDir, "medium.txt"), new string('A', 100));
            File.WriteAllText(Path.Combine(testDir, "large.txt"), new string('B', 500));
            
            var files = Directory.GetFiles(testDir);
            var fileSizes = files.Select(file => new FileInfo(file).Length);
            
            // Multiple LINQ operations for file analysis
            var totalSize = fileSizes.Sum();
            var averageSize = fileSizes.Average();
            var minSize = fileSizes.Min();
            var maxSize = fileSizes.Max();
            var fileCount = fileSizes.Count();
            
            Console.WriteLine("File Size Analysis:");
            Console.WriteLine($"Total files: {fileCount}");
            Console.WriteLine($"Total size: {totalSize} bytes");
            Console.WriteLine($"Average size: {Math.Round(averageSize, 1)} bytes");
            Console.WriteLine($"Smallest file: {minSize} bytes");
            Console.WriteLine($"Largest file: {maxSize} bytes");
            
            Directory.Delete(testDir, true);
        }
        catch (Exception ex) {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

The output of the above code is

File Size Analysis:
Total files: 3
Total size: 602 bytes
Average size: 200.7 bytes
Smallest file: 2 bytes
Largest file: 500 bytes

Conclusion

LINQ provides an elegant and concise way to calculate file sizes and perform statistical operations on file collections. By combining methods like Select(), Average(), and FileInfo, you can efficiently analyze file system data with minimal code, making file size estimation both simple and readable.

Updated on: 2026-03-17T07:04:36+05:30

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements