You must Sign In to post a response.
  • Category: .NET

    Compare Two text files

    Hi,

    I want to compare two text files and display the line and words that are being different.The files will be containing 1000 to 2000 lines.
    please assist me that the Easier or faster way of comparison in C#.

    Thanks
  • #768528
    Hi,

    We have many methods to do it. But i aware of Byte-Byte comparison. This is bit slow process if you would like go for it.
    Initially we can compare two files by loading one into our system and one keeping in the loop.

    This function will get executed with both the files are equal.

    public static bool EqualFile(FileInfo fileInfo1, FileInfo fileInfo2)
    {
    bool result;

    if (fileInfo1.Length != fileInfo2.Length)
    {
    result = false;
    }
    else
    {
    using (var file1 = fileInfo1.OpenRead())
    {
    using (var file2 = fileInfo2.OpenRead())
    {
    result = StreamsContentsAreEqual(file1, file2);
    }
    }
    }

    return result;
    }



    But the process is very slow definitely need patience for the execution on larger files.

    Thanks,
    Mani

  • #768541
    i think IEnumerable interface will help you more, see below snippet
    use File.ReadAllLines method to read all lines of textfiles then with the help of 'IEnumerable' we can put result in result text file

    String directory = @"C:\Whatever\";
    String[] linesA = File.ReadAllLines(Path.Combine(directory, "FileA-Database.txt"));
    String[] linesB = File.ReadAllLines(Path.Combine(directory, "FileB-Database.txt"));
    IEnumerable<String> onlyB = linesB.Except(linesA);
    File.WriteAllLines(Path.Combine(directory, "Result.txt"), onlyB);

    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • #768578
    You can use this code snippet for compare two text files

    string[] Lines1 = File.ReadAllLines(filePath1);
    string[] Lines2 = File.ReadAllLines(filePath2);
    for (int line = 0; line < Lines1.Length; line++)
    {
    if (line < Lines2.Length)
    {
    if (Lines1[line].Equals(Lines2[line]))
    {
    // lines from both the file are same
    }
    else
    {
    // Lines are not same
    }
    }
    else
    {
    // Doesnt exits in second file
    }


Sign In to post your comments