How to sort a text file by line length, including spaces, in C#

1 Answer

0 votes
using System;
using System.IO;
using System.Linq;

public class TextFileSorter
{
    /// <summary>
    /// Reads and prints each line of a text file to the console.
    /// </summary>
    /// <param name="filePath">The path to the text file to print.</param>
    public static void PrintFileContents(string filePath) {
        // Guard clause: Ensure the file exists
        if (!File.Exists(filePath)) {
            Console.WriteLine($"Error: The file '{filePath}' does not exist.");
            return;
        }

        try {
            // Read lines lazily and print each one
            foreach (string line in File.ReadLines(filePath)) {
                Console.WriteLine(line);
            }
        }
        catch (IOException ex) {
            Console.WriteLine($"An I/O error occurred: {ex.Message}");
        }
    }

    /// <summary>
    /// Sorts the lines of a text file by their length (including spaces) in ascending order.
    /// </summary>
    /// <param name="inputPath">The path to the source text file.</param>
    /// <param name="outputPath">The path where the sorted text file will be saved.</param>
    public static void SortFileByLineLength(string inputPath, string outputPath)
    {
        // Guard clause: Ensure the source file exists before proceeding
        if (!File.Exists(inputPath)) {
            throw new FileNotFoundException("The specified input file was not found.", inputPath);
        }

        try {
            // Read lines lazily, order them by string length (spaces included), 
            // and materialize into an array to release the input file lock.
            var sortedLines = File.ReadLines(inputPath)
                                  .OrderBy(line => line.Length)
                                  .ToArray();

            // Write the sorted lines to the destination file
            File.WriteAllLines(outputPath, sortedLines);

            Console.WriteLine($"File successfully sorted and saved to: {outputPath}");
        }
        catch (IOException ex) {
            Console.WriteLine($"An I/O error occurred while processing the file: {ex.Message}");
        }
    }

    public static void Main()
    {
        string sourceFile = "unsorted_data.txt";
        string targetFile = "sorted_data.txt";

        // Example execution
        try {
            // Optional: Create a dummy file for demonstration if it doesn't exist
            /*if (!File.Exists(sourceFile))  {
                File.WriteAllLines(sourceFile, new[] {
                    "Short line",
                    "This is a much longer line with spaces.",
                    "Medium line here",
                    "A"
                });
            }*/

            SortFileByLineLength(sourceFile, targetFile);
            PrintFileContents(sourceFile);
            Console.WriteLine("\n");
            PrintFileContents(targetFile);
        }
        catch (Exception ex) {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}


/*
run:

WhatsApp.Root - WhatsApp
ContextProject - Form1
Notepad - *private void button1_Click(object s - Notepad
ApplicationFrameHost - Settings
SystemSettings - Settings
msedge - Ask a question - CollectiveSolver and 61 more pages - Personal - Microsoft​ Edge
TextInputHost - Windows Input Experience
PowerToys.QuickAccess - PowerToys Quick Access (Preview)
devenv - ContextProject (Running) - Form1.cs - Microsoft Visual Studio


ContextProject - Form1
WhatsApp.Root - WhatsApp
SystemSettings - Settings
ApplicationFrameHost - Settings
TextInputHost - Windows Input Experience
Notepad - *private void button1_Click(object s - Notepad
PowerToys.QuickAccess - PowerToys Quick Access (Preview)
devenv - ContextProject (Running) - Form1.cs - Microsoft Visual Studio
msedge - Ask a question - CollectiveSolver and 61 more pages - Personal - Microsoft​ Edge

*/

 



answered Oct 29 by avibootz

Related questions

...