Invert A Text File - C# Programming Exercise

This C# exercise aims to teach how to manipulate text files and reverse their content using basic programming structures. In this exercise, you need to create a program that reads a text file, reverses its lines, and writes them into a new file with the same name but with the ".tnv" extension. The resulting file will contain the same lines as the original file but in reverse order: the first line will become the last, the second will become the penultimate, and so on.

To solve this exercise, it is recommended to read the file in two steps: first, count the number of lines in the file, and then store those lines in an array to later write them into the new file in reverse order. This exercise is perfect for practicing file handling and array usage in C#.

This challenge will allow you to improve your skills in text manipulation and understanding how to modify the content of a file programmatically.

 Category

File Management

 Exercise

Invert A Text File

 Objective

Create a program to "invert" the contents of a text file: create a file with the same name ending in ".tnv" and containing the same lines as the original file but in reverse order (the first line will be the last one, the second will be the penultimate, and so on, until the last line of the original file, which should appear in the first position of the resulting file).

Hint: the easiest way, using only the programming structures we know so far, is reading the source files two times: the first time to count the amount of lines in the file, and the second time to store them in an array.

 Write Your C# Exercise

// Importing necessary namespaces
using System; // Importing the System namespace for basic C# functionality
using System.IO; // Importing the IO namespace for file operations

public class InvertFileContents
{
    // Method to invert the contents of the text file
    public static void InvertFile(string inputFile)
    {
        // Generate the output file name by appending ".tnv" to the input file name
        string outputFile = Path.ChangeExtension(inputFile, ".tnv"); 

        // Read all lines from the input file
        string[] lines = File.ReadAllLines(inputFile); // Read all lines into an array

        // Open the output file for writing
        using (StreamWriter writer = new StreamWriter(outputFile)) // Open the output file in write mode
        {
            // Write the lines in reverse order
            for (int i = lines.Length - 1; i >= 0; i--) // Loop through the array in reverse order
            {
                writer.WriteLine(lines[i]); // Write the current line to the output file
            }
        }

        // Notify the user that the file inversion is complete
        Console.WriteLine($"File '{inputFile}' has been inverted and saved as '{outputFile}'."); // Print success message
    }
}

class Program
{
    // Main method where the program execution starts
    static void Main(string[] args)
    {
        // Check if the user provided the file name as an argument
        if (args.Length < 1) // If no file name is provided
        {
            Console.WriteLine("Please provide the input text file."); // Prompt user to provide the file
            return; // Exit the program if no file is provided
        }

        string inputFile = args[0]; // Assign the input file name from the command line argument

        // Check if the input file exists
        if (!File.Exists(inputFile)) // If the input file doesn't exist
        {
            Console.WriteLine($"The file '{inputFile}' does not exist."); // Print error message
            return; // Exit the program if the file doesn't exist
        }

        // Call the method to invert the contents of the file
        InvertFileContents.InvertFile(inputFile); // Invert the file contents and save the result

    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Reading a binay file (2 - GIF)

    This C# exercise aims to teach how to check the validity of a GIF image file. In this exercise, you need to create a program that reads the first four bytes of...

  •  Friends database, using files

    This C# exercise aims to expand a friends database by allowing data to be loaded from a file at the beginning of each session and saved to...

  •  Pascal to C# translator

    This C# exercise involves creating a basic Pascal to C# translator. The program should accept code written in Pascal and convert it to an equival...

  •  Convert a text file to uppercase

    This C# exercise involves creating a program that reads a text file and dumps its content into another file, making a transformation in the process. The transformatio...

  •  Convert any file to uppercase

    This C# exercise involves creating a program that reads a file of any kind and dumps its content into another file, applying a transformation in the process. The tran...

  •  File inverter

    This C# exercise involves creating a program to "invert" a file. The program must take an original file and create a new one with the same name but with the ".inv" ex...