Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Locate and Insert empty/new lines when comparing two text files

Status
Not open for further replies.

djfrear

Programmer
Jul 11, 2007
83
GB
Lets say, for example, I have two simple text files which contain 100 lines and 150 line respectively.

If they are identical apart from 50 lines from line 90 through 140 in the second file how can I find where that difference begins and ends then insert blank lines into the first file giving you 150 lines in both files, just with a large empty gap in the first.

This is the same sort of thing programs such as WinMerge do.
 
Here is the brute force way

I beleive there is a better way opening the files into a DataSet and running left join queries and such, I may look into that given more time.

public static void CompareFilesBrute(string bigFile, string littleFile, string finishfile)
{
StreamWriter sw = new StreamWriter(finishfile);
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader BigSr = new StreamReader(bigFile))
{
using (StreamReader LittleSr = new StreamReader(littleFile))
{
string BigLine;
string LittleLine;

while ((LittleLine = LittleSr.ReadLine()) != null)
{
BigLine = BigSr.ReadLine();

while (BigLine != LittleLine)
{
sw.WriteLine("");
BigLine = BigSr.ReadLine();
}
sw.WriteLine(BigLine);

}
}
}
}
catch (Exception e)
{
throw new Exception("Error in compare", e);
}
finally
{
sw.Flush();
sw.Close();
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top