C# - Compare content of two files using StreaReader class

Learn, how to compare the content of two files using StreaReader class in C#? By Nidhi Last updated : April 03, 2023

Compare content of two files

Here, we will read the content of two files and then compare then data of both files.

C# program to compare the content of two files

The source code to compare the content of two files using the StreamReader class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to compare the content of 
//two files using StreamReader class.

using System;
using System.Threading;
using System.IO;

class Demo
{
    public static string Read(string filename)
    {
        string data;

        try
        {
            FileStream s = new FileStream(filename, FileMode.Open);
            StreamReader r = new StreamReader(s);

            data = r.ReadToEnd();
            r.Close();
            s.Close();
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine(e.Message);
            return null;
        }
        return data;
    }
    static void Main(string[] arg)
    {
        string data1 = "";
        string data2 = "";

        data1 = Read("d:/file1.txt");
        data2 = Read("d:/file2.txt");

        if (data1 == null || data2 == null)
            return;

        if (data1 == data2)
            Console.WriteLine("Content of files is similar");
        else
            Console.WriteLine("Content of files is not similar");
    }
}

Output

Content of files is similar
Press any key to continue . . .

Explanation

Here, we created a class Demo that contains two static methods Read() and Main(). In the Read() method, we read the data from the file and return to the calling method, here we wrote code into the "try" block, if the file does not exist then we handled and exception and return value "null" to the calling method.

In the Main() method, we created two local variables data1 and data2, and then read the content of two specified files using the Read() method. if any specified file does not exist then the Read() method returns the "null" value then we did not compare the content of the file, if both files exist then we compare the content of files and print the appropriate message on the console screen.

C# Files Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.