0

I have written some code to compare 2 files and write their common lines to a 3rd file. For some reason though the 3rd file which contains the common lines has ALL the common lines written to it on 1 line. This should really be 1 new line per common line..I have even tried adding Console.WriteLine('\n'); to add a new line to separate the common lines but this isn't helping. Any ideas as to what is wrong?

    //This program will read  files and compares to see if they have a line in common
    //if there is a line in common then it writes than common line to a new file
  static void Main(string[] args)
    {

        int counter = 0;
        string line;
        string sline;
        string[] words;
        string[] samacc = new string[280];


        //first file to compare
        System.IO.StreamReader sfile =
           new System.IO.StreamReader("C:\\Desktop\\autoit\\New folder\\userlist.txt");
        while ((sline = sfile.ReadLine()) != null)
        {
            samacc[counter] = sline;
            Console.WriteLine();

            counter++;
        }

        sfile.Close();

        //file to write common lines to.
        System.IO.StreamWriter wfile = new System.IO.StreamWriter("C:\\Desktop\\autoit\\New folder\\KenUserList.txt");

        counter = 0;

        //second file to compare
        System.IO.StreamReader file =
           new System.IO.StreamReader("C:\\Desktop\\autoit\\New folder\\AllUserHomeDirectories.txt");
        while ((line = file.ReadLine()) != null)
        {
            words = line.Split('\t');

            foreach (string i in samacc)
            {
                if (words[0] == i)
                {

                    foreach (string x in words)
                    {
                        wfile.Write(x);
                        wfile.Write('\t');
                    }
                    Console.WriteLine('\n');
                }
            }

        }

        file.Close();

        wfile.Close();
        // Suspend the screen.
        Console.ReadLine();


    }
4

2 回答 2

6

更改Console.WriteLine('\n');wfile.WriteLine('\n');

于 2013-05-15T15:48:49.347 回答
1

您可以以更好的方式做到这一点:

var file1 = File.ReadLines(@"path1");
var file2 = File.ReadLines(@"path2");

var common = file1.Intersect(file2); //returns all lines common to both files

File.WriteAllLines("path3", common);
于 2013-05-15T15:49:52.323 回答