Compare lines of 2 txt files in C#
I would like to compare lines 2 txt files. I think to do loops, but how? Here is my code to read in 2 files:
Code:
StreamReader li = new StreamReader("list.txt" );
StreamReader li2= new StreamReader ("list2.txt" );
string li = li.ReadLine();
string li2 = li2.ReadLine();
while (li != null && li2 != null)
{
Console.Write(li);
Console.Write(li2);
}
Re: Compare lines of 2 txt files in C#
You want to compare it to say? Display only those that are similar? You are aware that there are tools (and libs) made for that?
Re: Compare lines of 2 txt files in C#
I think you need to modify your code with something like this:
Code:
using (StreamReader li = new StreamReader("list.txt" ))
using (StreamReader li2 = new StreamReader("list2.txt" ))
{
while (true)
{
if (li.EndOfStream || li2.EndOfStream)
break;
string liTxt = li.ReadLine();
string li2Txt = li2.ReadLine();
if (!liTxt.Equals(li2Txt))
Console.WriteLine("Lines different!!!" );
}
}
Re: Compare lines of 2 txt files in C#
Thanks for your code Ashok but I am sorry it fails at while loop. Can you enlighten me where is the problem? I am unable to rectify it.
Re: Compare lines of 2 txt files in C#
That may be the error somewhere else in your program, just recheck your code. One more thing, you can also use do while loop which is much handy sometimes.