File Inverter - C# Programming Exercise

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" extension, containing the same bytes as the original file but in reverse order. That is, the first byte from the original file will be the last in the new file, the second byte will be the penultimate, and so on, until the last byte of the original file appears in the first position of the resulting file. This exercise is a great opportunity to learn how to work with binary files in C# and manipulate their content.

The program should be able to read a binary file, reverse the order of the bytes, and create a new file with the result. To achieve this, the BinaryReader class can be used to read the data, and the BaseStream.Length property helps obtain the file's length. Additionally, the Seek method allows jumping to a specific position within the file, which makes it possible to read the bytes in reverse order. This exercise helps understand how to work with files of varying sizes and efficiently manipulate their bytes in C#.

The .cs file must include a comment with your name, ensuring that the code is your own. This exercise also teaches how to use reading positions in binary files with SeekOrigin, which is crucial when working with files in C#.

 Category

File Management

 Exercise

File Inverter

 Objective

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

You must deliver only the ".cs" file, which should contain a comment with your name.

Hint: To know the length of a binary file (BinaryReader), you can use "myFile.BaseStream.Length" and you can jump to a different position with "myFile.BaseStream.Seek(4, SeekOrigin.Current);"

The starting positions we can use are: SeekOrigin.Begin, SeekOrigin.Current- o SeekOrigin.End

 Write Your C# Exercise

// Import the System namespace for basic functionality
using System;  

// Import the IO namespace for file handling
using System.IO;  

class FileInverter
{
    static void Main(string[] args)
    {
        // Ask the user to enter the path of the file to invert
        Console.WriteLine("Enter the path of the file to invert:");  
        
        // Get the file path entered by the user
        string inputFilePath = Console.ReadLine();  

        // Start of try block to catch any file or IO errors
        try
        {
            // Open the original file in read mode using BinaryReader
            using (BinaryReader reader = new BinaryReader(File.Open(inputFilePath, FileMode.Open)))
            {
                // Get the total length of the file (in bytes)
                long fileLength = reader.BaseStream.Length;  

                // Generate the output file path by appending ".inv" to the original file name
                string outputFilePath = inputFilePath + ".inv";  

                // Open the output file in write mode using BinaryWriter
                using (BinaryWriter writer = new BinaryWriter(File.Open(outputFilePath, FileMode.Create)))
                {
                    // Loop through the file in reverse order, from the last byte to the first
                    for (long i = fileLength - 1; i >= 0; i--) 
                    {
                        // Move the reader to the byte at the current position
                        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);  
                    }
                }
            }

            // Inform the user that the inversion process is complete
            Console.WriteLine("File has been successfully inverted and saved as: " + inputFilePath + ".inv");
        }
        catch (Exception ex)  // Catch any exceptions that may occur during file operations
        {
            // Print the exception message if an error occurs
            Console.WriteLine("An error occurred: " + ex.Message);  
        }
    }
}

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

  •  File encrypter

    This C# exercise involves creating a program to encrypt a text file into another text file. The program should be able to read the content of a text file, apply an en...

  •  Count words

    This C# exercise involves creating a program to count the number of words stored in a text file. The program should read the content of a text file, process it, and c...

  •  BMP width and height, BinaryReader

    This C# exercise involves creating a program to display the width and height of a BMP file using a BinaryReader. The program should read the BMP file header an...

  •  TXT to HTML translator

    This C# exercise involves creating a "Text to HTML converter". The program should read a source text file and create an HTML file from its contents. The destination f...

  •  Invert binary file V2

    This C# exercise involves creating a program to "invert" a file using a FileStream. The program should create a file with the same name as the original file, b...

  •  BMP width & height, FileStream

    This C# exercise involves creating a program that reads a BMP file using a FileStream and displays its width and height. The BMP format has a spe...