Programming Course in C# ¡Free!

File inverter

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

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


Output



Solution


using System;
using System.IO;

public class FileInverter
{
public static void Main()
{
BinaryReader fileR = new BinaryReader(
File.Open("data.dat", FileMode.Open));

BinaryWriter fileW = new BinaryWriter(
File.Open("data.data.inverter", FileMode.Create));

int size = fileR.BaseStream.Length;

for (int i = size - 1; i >= 0; i--)
{
fileR.BaseStream.Seek(i, SeekOrigin.Begin);
byte b = fileR.ReadByte();

fileW.Write(b);
}

fileR.Close();
fileW.Close();
}
}