Programming Course in C# ¡Free!

Encrypt a BMP file

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

Create a program to encrypt/decrypt a BMP image file, by changing the "BM" mark in the first two bytes with MB and vice versa.

Use the advanced FileStream constructor to allow simultaneous reading and writing.


Output



Solution


using System;
using System.IO;

class EncryptBMP
{
static void Main()
{
Console.Write("Enter the name: ");
string name = Console.ReadLine();

if (!File.Exists(name))
{
Console.WriteLine("Not exists");
return;
}

try
{
FileStream file = File.Open(name, 
FileMode.Open,FileAccess.ReadWrite);
byte b1 = (byte)file.ReadByte();
byte b2 = (byte)file.ReadByte();

if ((Convert.ToChar(b1) != 'B')
|| (Convert.ToChar(b2) != 'M'))
Console.WriteLine("not bmp valid");
else
{
file.Seek(0, SeekOrigin.Begin);
file.WriteByte((byte)'M');
file.WriteByte((byte)'B');
}
file.Close();
}
catch (Exception)
{
Console.WriteLine("Error");
}
}
}