-1

I need to compare 2 text files that includes several lines. 1st file consists of 63 lines, and the second one of 10. So, I need to compare them and delete if the first one includes the second, that is if those 10 lines from the second file are included to the 1st file, delete them from the 1st file.

        string line = null;
        string[] lines = File.ReadAllLines(@"D:\trash.txt").ToArray();
        using (StreamReader file = new StreamReader(@"D:\write.txt"))
        {
            while ((line = file.ReadLine()) != null)
            {
                for (int i = 0; i < lines.Length; i++)
                {
                    if (!line.Contains(lines[i]))
                    {
                        using (StreamWriter writer = new StreamWriter(@"D:\numbers.txt", true))
                        {
                            writer.WriteLine(line);
                        }
                    }
                }
            }
        }

I ve tried to compare them like this, and not write same lines to new file. But as you can see, this code, if !line.Contains(lines[i]) is true, writes one line 10 times, cause lines.Length equals to 10

Fazka
  • 5
  • 4

1 Answers1

0

simple approach:

for each line x in file 1:
for each line y in file 2:
compare lines x and y, and if they match, delete line x from file 1

better approach if the number of lines to test against (file 2) is small enough or if enough memory is available:

load all lines from file 2 into a hashtable
for each line x from file 1:
check if the hashtable contains x, if yes, delete line x from file 1

DarkSquirrel42
  • 10,167
  • 3
  • 20
  • 31