我编写了一些代码来比较2个文件并将它们的公共行写入第3个文件。由于某种原因,虽然包含公共线的第3个文件具有在1行上写入的所有公共线。这应该是每个公共行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();
}
答案 0 :(得分:6)
将Console.WriteLine('\n');
更改为wfile.WriteLine('\n');
答案 1 :(得分: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);