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
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the name of the file to invert:");
string fileName = Console.ReadLine();
try
{
if (!File.Exists(fileName))
{
Console.WriteLine("Error: The specified file does not exist.");
return;
}
using (FileStream inputFile = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
using (FileStream outputFile = new FileStream(fileName + ".inv", FileMode.Create, FileAccess.Write))
{
long fileLength = inputFile.Length;
for (long i = fileLength - 1; i >= 0; i--)
{
inputFile.Seek(i, SeekOrigin.Begin);
int byteValue = inputFile.ReadByte();
outputFile.WriteByte((byte)byteValue);
}
}
}
Console.WriteLine($"The file '{fileName}' has been successfully inverted and saved as '{fileName}.inv'.");
}
catch (Exception ex)
{
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