Exercise
File comparer
Objetive
Create a C# program to tell if two files (of any kind) are identical (have the same content).
Example Code
using System;
using System.IO;
namespace FileComparer
{
class Program
{
static void Main(string[] args)
{
bool equal = true;
FileStream myFile1;
byte[] dataFile1;
FileStream myFile2;
byte[] dataFile2;
Console.Write("Enter the name of file1: ");
string fileName1 = Console.ReadLine();
Console.Write("Enter the name of file2: ");
string fileName2 = Console.ReadLine();
if ((!File.Exists(fileName1)) || (!File.Exists(fileName2)))
{
Console.WriteLine("The file 1 or file 2 not exists!!!");
return;
}
try
{
myFile1 = File.OpenRead(fileName1);
dataFile1 = new byte[myFile1.Length];
myFile1.Read(dataFile1, 0, (int)myFile1.Length);
myFile1.Close();
myFile2 = File.OpenRead(fileName2);
dataFile2 = new byte[myFile2.Length];
myFile2.Read(dataFile2, 0, (int)myFile2.Length);
myFile2.Close();
if (myFile1.Length == myFile2.Length)
for (int i = 0; i < dataFile1.Length; i++)
if (dataFile1[i] != dataFile2[i])
equal = false;
else
equal = false;
if (equal)
Console.WriteLine("The {0} is equal {1}", fileName1, fileName2);
else
Console.WriteLine("The {0} not is equal {1}", fileName1, fileName2);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error: {0}!!!", e.Message);
}
}
}
}