Invert Binary File V2 - C# Programming Exercise

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, but with the ".inv" extension at the end, 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 appears in the first position of the resulting file. This exercise is a great way to learn how to work with binary file streams and manipulate the contents of a file at the byte level in C#.

The program should use a FileStream to read the original file byte by byte and then write the bytes to the output file in reverse order. This exercise also teaches you how to work with input and output data streams, a crucial skill for handling files in real-world applications. By completing this exercise, you will understand how to handle binary files and invert the contents of a file using a data stream.

This exercise is particularly useful for understanding how to manipulate files at a lower level in C# using classes like FileStream, which allow reading and writing binary data directly to files. It's an important skill when working with large files or in situations where precise control over how data is read and written to a file is required.

 Category

File Management

 Exercise

Invert Binary File V2

 Objective

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.

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

 Write Your C# Exercise

// Import the necessary namespaces for file handling
using System;
using System.IO;

class InvertBinaryFile
{
    // Main method where the program starts
    static void Main(string[] args)
    {
        // Prompt the user to enter the path of the binary file
        Console.WriteLine("Enter the path of the binary file:");

        // Get the file path from user input
        string filePath = Console.ReadLine();

        // Check if the file exists
        if (File.Exists(filePath))
        {
            // Create the path for the new file by appending ".inv" to the original file name
            string invertedFilePath = Path.ChangeExtension(filePath, ".inv");

            try
            {
                // Open the original file for reading in binary mode
                using (FileStream inputFile = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    // Get the length of the file
                    long fileLength = inputFile.Length;

                    // Open the new file for writing in binary mode
                    using (FileStream outputFile = new FileStream(invertedFilePath, FileMode.Create, FileAccess.Write))
                    {
                        // Loop through the original file from the last byte to the first byte
                        for (long i = fileLength - 1; i >= 0; i--)
                        {
                            // Move the read position to the current byte in the input file
                            inputFile.Seek(i, SeekOrigin.Begin);

                            // Read the byte at the current position
                            byte[] byteToWrite = new byte[1];
                            inputFile.Read(byteToWrite, 0, 1);

                            // Write the byte to the output file
                            outputFile.Write(byteToWrite, 0, 1);
                        }
                    }
                }

                // Inform the user that the file has been successfully inverted
                Console.WriteLine("The binary file has been successfully inverted.");
            }
            catch (Exception ex)  // Catch any errors that occur
            {
                // Output an error message if an exception is thrown
                Console.WriteLine("An error occurred: " + ex.Message);
            }
        }
        else
        {
            // Inform the user if the specified file doesn't exist
            Console.WriteLine("The specified file does not exist.");
        }
    }
}

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

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

  •  File copier

    This C# exercise involves creating a program that copies a source file to a destination file using a FileStream and a block size of 512 KB. The program should ...

  •  MP3 reader

    This C# exercise is about the ID3 specifications, which apply to any file or audiovisual container, but are primarily used with audio containers. There are three comp...

  •  C to C# converter

    This exercise consists of creating a program that converts simple C programs, such as the following one, into C#, ensuring that the resulting program compiles ...

  •  File splitter

    This exercise involves creating a program that splits a file (of any kind) into pieces of a certain size. The program should receive the file name and the desired size of th...

  •  Encrypt a BMP file

    This exercise involves creating a program to encrypt and decrypt a BMP image file by changing the "BM" mark in the first two bytes to "MB" and vice versa. The program should...