Quote Originally Posted by WinnitBaker View Post
Hi guys, im trying to make a console application which reads 2 text files and outputs it into one text file. The outputted text file needs to remove any replicates of data from the 2 text files. Was wondering if people could tell me whats wrong with my code -

Code:
while (!sr.EndOfStream)
                    {
                        strList1.Add(sr.ReadLine());

                    }

                    while (!sr2.EndOfStream)
                    {
                        strList2.Add(sr2.ReadLine());
                    }

                    foreach (string st in strList2)
                    {

                        for (int i = 0; i < strList2.Count; i++)
                        {
                            if (sr.ReadLine() == st)
                            {
                                break;
                            }
                                sw.WriteLine(st);
  
                        }

                        foreach (string s in strList1)
                        {
                            sw.WriteLine(s);
                        }
You can compare while reading the second file. Also if your purpose is to write 1 new file containing all words from both files excluding writing the duplicates of a word you can accomplish it with 1 list.

Code:
   // Read all of first file content and save it to a list
   while (!sr.EndOfStream)
   {
      wordList.Add(sr.ReadLine());
   }

   // Read file 2 and check strings that are duplicates
   while (!sr2.EndOfStream)
   {
      // Temporary string to use for comparing
      string temp = sr2.ReadLine();

      // Check if its a new word and if so save it to the list
      If (!wordList.Contains(temp)
      {
          wordList.Add(temp);
      }
    }

   // Write out all words found in both files without writing words twice
   foreach (string s in wordList)
   {
      // Instead of writing out you could save to a new file
      Console.WriteLine(s);
   }
The code should read both files. First saving all words found in file1 and after that while reading file 2 it checks if the word is a duplicate or a new word. If its a new word it saves it to a list that can be used later.

If you are trying to remove duplicate words from the list all together you can remove it from the list to exclude it from saving to your new file by using the remove function from List<T>


In you code I am not sure why you are using sr.ReadLine() inside your foreach loop as it should have already served its function when it was reading the first file. I think what you were looking to do was strList1[i]. Also keep in mind the code you have will write out the words multiple times to a file because of the for loop inside the foreach loop