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
Show 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