2013-05-15 51 views
0

我寫了一些代碼來比較2個文件,並將它們的通用行寫入第3個文件。由於某些原因,雖然包含公共行的第三個文件在所有行上寫入了所有公用行。這應該是真正的每行1個新行。我甚至嘗試添加Console.WriteLine('\ n');添加一條新線來分隔通用線路,但這不起作用。關於什麼是錯的任何想法?爲什麼這個文件上沒有換行符?

//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(); 


    } 

回答

6

變化Console.WriteLine('\n');wfile.WriteLine('\n');

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); 
+0

謝謝!這也將工作!這對我來說現在是一個快速的小修復,所以我並不太擔心這個腳本是高效或簡單的。只需要使用它一次,永遠不會再使用它。 – Harmond

相關問題