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 a new file in reverse order. The new file will have the same name as the original file but with the extension .inv. Each byte in the new file will be in the reverse order compared to the original file. For example, the first byte of the resulting file will be the last byte of the original file, the second byte will be the second last, and so on, until the last byte of the original file appears first in the new file. This program is useful for reversing file contents, such as for data manipulation or testing.



Group

File Handling in C#

Objective

1. The user will provide the name of the file to be inverted.
2. The program will open the original file using FileStream to read its bytes.
3. The program will then create a new file with the same name as the original file but with the .inv extension.
4. It will write the bytes of the original file to the new file in reverse order.
5. After completing the process, the program will display a message indicating the success of the operation.

Create a program to "invert" a file using a "FileStream". The program should 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 of the resulting file should be the last byte of the original file, the second byte should 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 FileInverter
{
    // Main method to run the program
    static void Main(string[] args)
    {
        // Ask the user for the name of the file to invert
        Console.WriteLine("Please enter the name of the file to invert:");

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

        try
        {
            // Check if the file exists
            if (!File.Exists(fileName))
            {
                Console.WriteLine("Error: The specified file does not exist.");
                return;
            }

            // Create a FileStream to read the original file
            using (FileStream inputFile = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                // Create a FileStream to write the inverted file with ".inv" extension
                using (FileStream outputFile = new FileStream(fileName + ".inv", FileMode.Create, FileAccess.Write))
                {
                    // Get the total length of the original file
                    long fileLength = inputFile.Length;

                    // Loop through the original file in reverse order
                    for (long i = fileLength - 1; i >= 0; i--)
                    {
                        // Move the stream position to the current byte to read
                        inputFile.Seek(i, SeekOrigin.Begin);

                        // Read the byte at the current position
                        int byteValue = inputFile.ReadByte();

                        // Write the byte to the new file in reverse order
                        outputFile.WriteByte((byte)byteValue);
                    }
                }
            }

            // Inform the user that the inversion is complete
            Console.WriteLine($"The file '{fileName}' has been successfully inverted and saved as '{fileName}.inv'.");
        }
        catch (Exception ex)
        {
            // Handle any errors that may occur during the process
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

 Output

//If the user enters example.txt and the file contains the following bytes:
Hello, world!

//The program will create a file named example.txt.inv with the reversed content:
!dlrow ,olleH

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#.

  • 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...

  • Copy Source File to Destination File Using FileStream in C#

    This program copies a source file to a destination file using FileStream in C#. The file is read and written in blocks of 512 KB at a time to handle large files efficiently. The pr...

  • Tag Reader for Audio Files in C#

    This program reads and extracts the ID3 version 1 tags from an audio file, specifically the last 128 bytes of the file, which contain metadata information such as the title, artist...

  • Simple C to C# Converter

    This program is designed to convert simple C programs into C# code. It takes a C program as input and translates it into a corresponding C# program that compiles and runs correctly...

  • File Splitter Program in C#

    This program allows you to split a file of any type into smaller pieces of a specified size. The program takes two parameters: the name of the file to split and the size (in bytes)...

  • BMP Image File 'Encrypt-Decrypt' Program in C#

    This program allows you to encrypt and decrypt BMP image files by manipulating the "BM" mark located in the first two bytes of the file. The program swaps the "BM" marker at the be...