File Comparer - C# Programming Exercise

This exercise involves creating a C# program that determines if two files (of any kind) are identical, meaning they have the same content. The program should compare the files byte by byte and check if they are the same. This exercise reinforces the use of FileStream and byte-by-byte comparison to perform accurate file comparisons, which is essential in scenarios where duplicate files need to be identified or data integrity needs to be verified. Additionally, it helps in understanding how to efficiently work with binary files in C#.

 Category

File Management

 Exercise

File Comparer

 Objective

Create a C# program to tell if two files (of any kind) are identical (have the same content).

 Write Your C# Exercise

// Import necessary namespaces for file handling
using System; // Basic input/output operations
using System.IO; // FileStream for reading files
using System.Text; // StringBuilder for efficient string handling

class FileComparer // Main class for the file comparison program
{
    static void Main(string[] args) // Entry point of the program
    {
        // Check if the correct number of arguments (input files) are provided
        if (args.Length != 2) // If not enough arguments are provided
        {
            Console.WriteLine("Usage: FileComparer  "); // Show usage instructions
            return; // Exit the program if the arguments are incorrect
        }

        string file1 = args[0]; // The first file name to compare
        string file2 = args[1]; // The second file name to compare

        // Check if both files exist
        if (!File.Exists(file1)) // If the first file does not exist
        {
            Console.WriteLine($"Error: The file {file1} does not exist."); // Inform the user about the missing file
            return; // Exit the program if the first file is missing
        }

        if (!File.Exists(file2)) // If the second file does not exist
        {
            Console.WriteLine($"Error: The file {file2} does not exist."); // Inform the user about the missing file
            return; // Exit the program if the second file is missing
        }

        try
        {
            // Open both files for reading using FileStream
            using (FileStream fs1 = new FileStream(file1, FileMode.Open, FileAccess.Read)) // Open the first file
            using (FileStream fs2 = new FileStream(file2, FileMode.Open, FileAccess.Read)) // Open the second file
            {
                // Compare file lengths first
                if (fs1.Length != fs2.Length) // If the file sizes are different
                {
                    Console.WriteLine("The files are different (different sizes)."); // Inform the user about different sizes
                    return; // Exit the program if the sizes don't match
                }

                // Use byte arrays to read the files in chunks
                byte[] buffer1 = new byte[1024]; // Buffer to hold data from the first file
                byte[] buffer2 = new byte[1024]; // Buffer to hold data from the second file

                int bytesRead1, bytesRead2; // Variables to store the number of bytes read from each file

                // Compare the files byte by byte
                while ((bytesRead1 = fs1.Read(buffer1, 0, buffer1.Length)) > 0) // Read from the first file
                {
                    bytesRead2 = fs2.Read(buffer2, 0, buffer2.Length); // Read from the second file

                    // If the number of bytes read is different, the files are different
                    if (bytesRead1 != bytesRead2)
                    {
                        Console.WriteLine("The files are different (different lengths in chunks)."); // Inform the user about the discrepancy
                        return; // Exit the program if the chunk sizes don't match
                    }

                    // Compare the bytes from both buffers
                    for (int i = 0; i < bytesRead1; i++) // Loop through the bytes read
                    {
                        if (buffer1[i] != buffer2[i]) // If a byte doesn't match
                        {
                            Console.WriteLine("The files are different (mismatch found)."); // Inform the user about the mismatch
                            return; // Exit the program if any byte doesn't match
                        }
                    }
                }

                // If all checks pass, the files are identical
                Console.WriteLine("The files are identical."); // Inform the user that the files are the same
            }
        }
        catch (Exception ex) // Catch any exceptions that occur during file reading or comparison
        {
            Console.WriteLine($"An error occurred: {ex.Message}"); // Display the error message
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Display BPM on console

    This exercise involves creating a C# program to decode an image file in the Netpbm format (specifically, the P1 format, which is for black and white ima...

  •  PCX width and height

    This exercise involves creating a C# program to check if a file is a PCX image and, if so, extract and display the image's dimensions (width and height). To do...

  •  Extract text from a binary file

    This exercise involves creating a C# program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The program sh...

  •  C# to Pascal converter

    This exercise involves creating a C# program that converts simple C# programs to their equivalent in the Pascal language. The program should read C# cod...

  •  Dump

    This exercise involves creating a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes per row and 24 rows per screen. The program should pause a...

  •  DBF extractor

    This exercise involves creating a program that displays the list of fields stored in a DBF file. The DBF format is used by the old dBase database manager and is still suppor...