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;
using System.Text;
class FileComparer
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: FileComparer ");
return;
}
string file1 = args[0];
string file2 = args[1];
if (!File.Exists(file1))
{
Console.WriteLine($"Error: The file {file1} does not exist.");
return;
}
if (!File.Exists(file2))
{
Console.WriteLine($"Error: The file {file2} does not exist.");
return;
}
try
{
using (FileStream fs1 = new FileStream(file1, FileMode.Open, FileAccess.Read))
using (FileStream fs2 = new FileStream(file2, FileMode.Open, FileAccess.Read))
{
if (fs1.Length != fs2.Length)
{
Console.WriteLine("The files are different (different sizes).");
return;
}
byte[] buffer1 = new byte[1024];
byte[] buffer2 = new byte[1024];
int bytesRead1, bytesRead2;
while ((bytesRead1 = fs1.Read(buffer1, 0, buffer1.Length)) > 0)
{
bytesRead2 = fs2.Read(buffer2, 0, buffer2.Length);
if (bytesRead1 != bytesRead2)
{
Console.WriteLine("The files are different (different lengths in chunks).");
return;
}
for (int i = 0; i < bytesRead1; i++)
{
if (buffer1[i] != buffer2[i])
{
Console.WriteLine("The files are different (mismatch found).");
return;
}
}
}
Console.WriteLine("The files are identical.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}