Invert File Content and Save in Reverse Order in C#

This program is designed to read a binary file and create a new file with the same name but with a ".inv" extension. The new file will contain the same bytes as the original file, but in reverse order. This means the first byte of the original file will become the last byte in the new file, the second byte will become the second-last byte, and so on until the last byte of the original file, which will become the first byte in the new file.

The program uses BinaryReader and BinaryWriter to read and write binary data efficiently. The length of the file is determined using BaseStream.Length, and the byte positions are managed using Seek to navigate through the file.



Group

File Handling in C#

Objective

1. The program reads the content of the binary file.
2. The file is opened for reading, and its length is determined.
3. The program then writes a new file with the bytes in reverse order.
4. The new file is saved with the same name as the original, but with a ".inv" extension.
5. Proper error handling should be included in case the file cannot be read or written to.

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

Example C# Exercise

 Copy C# Code
using System;
using System.IO;

class InvertFileContent
{
    // Main method to execute the program
    static void Main(string[] args)
    {
        // Ask the user for the input file name
        Console.WriteLine("Please enter the name of the file to invert:");

        // Read the name of the input file from the user
        string inputFileName = Console.ReadLine();

        // Generate the name of the output file by appending ".inv"
        string outputFileName = Path.GetFileNameWithoutExtension(inputFileName) + ".inv" + Path.GetExtension(inputFileName);

        try
        {
            // Open the input file for reading in binary mode
            using (BinaryReader reader = new BinaryReader(File.Open(inputFileName, FileMode.Open)))
            {
                // Open the output file for writing in binary mode
                using (BinaryWriter writer = new BinaryWriter(File.Open(outputFileName, FileMode.Create)))
                {
                    // Get the length of the input file in bytes
                    long fileLength = reader.BaseStream.Length;

                    // Loop through the file in reverse order
                    for (long i = fileLength - 1; i >= 0; i--)
                    {
                        // Move to the byte at position i in the file
                        reader.BaseStream.Seek(i, SeekOrigin.Begin);

                        // Read the byte at the current position
                        byte currentByte = reader.ReadByte();

                        // Write the byte to the output file
                        writer.Write(currentByte);
                    }

                    // Notify the user that the operation was successful
                    Console.WriteLine($"The content has been successfully inverted and saved to {outputFileName}");
                }
            }
        }
        catch (FileNotFoundException)
        {
            // If the file is not found, inform the user
            Console.WriteLine("Error: The specified file could not be found.");
        }
        catch (Exception ex)
        {
            // Handle any other unexpected errors
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

 Output

//If the input file data.bin contains the following bytes (in hexadecimal format):
01 02 03 04 05

//The output file data.inv will contain the reversed bytes:
05 04 03 02 01

Share this C# Exercise

More C# Practice Exercises of File Handling in C#

Explore our set of C# Practice 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#.

  • Text File Encryption Program in C#

    This program is designed to encrypt a text file and save the encrypted content into another text file. The encryption method used here is a simple character shifting technique, whe...

  • Word Count Program for Text File in C#

    This program is designed to read a text file and count the number of words it contains. A word is considered any sequence of characters separated by spaces, newlines, or punctuatio...

  • Display BMP File Width and Height using BinaryReader in C#

    This program is designed to read a BMP (Bitmap) image file and display its width and height. The BMP file format has a specific header structure, which contains important informati...

  • File Text to HTML Converter in C#

    This program is a "Text to HTML Converter" that reads the contents of a source text file and converts it into an HTML file. The program will take the text file and process its cont...

  • File Inverter Using FileStream in C#

    This program takes a file and creates a new file where the bytes are inverted. The program reads the contents of the original file using a FileStream, then writes these contents to...

  • Display Width and Height of a BMP File Using FileStream in C#

    This program reads the header of a BMP (Bitmap) file and extracts the width and height of the image using FileStream. It uses the structure of the BMP header, where the width and h...