逐行比较两个文本文件 [英] Compare two text files line by line

查看:29
本文介绍了逐行比较两个文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面我描述了一个示例场景:

Beneath here i described a example Scenario:

FileA-Database.txt"包含以下名称:

"FileA-Database.txt" contains the following names:

KB200

KB300

KB400

FileB-Slave.txt"包含以下名称:

"FileB-Slave.txt" contains the following names:

KB600

KB200

KB400

KB700

我想将FileA-Database.txt"与FileB-Slave.txt"进行比较,并让FileA-Database.txt"文件中的缺失值自动填充,我还需要显示缺失值在名为Results.txt"的文本文件中.

I want to compare the "FileA-Database.txt" with "FileB-Slave.txt" and let the missing values be filled in automatically in the "FileA-Database.txt" file also i need to display the missing values in a text file called "Results.txt".

代码需要兼容 C#(框架 4.0+)!

The code needs to be compatible with C# (framework 4.0+) please!.

我需要一个简单的方法,我的方法与我想要的方式不完全一样:

I need a simple approach, mine doesnt work exactly the way i want it to:

    private void button_compare_Click(object sender, EventArgs e)
        {
            string fileA, fileB, fileC;
            fileA = "database-critical.txt";
            fileB = "patchlist.txt";
            fileC = "result.txt";

            string alphaFilePath = fileA;

            List<string> alphaFileContent = new List<string>();

            using (FileStream fs = new FileStream(alphaFilePath, FileMode.Open))
            using(StreamReader rdr = new StreamReader(fs))
            {
                while(!rdr.EndOfStream)
                {
                    alphaFileContent.Add(rdr.ReadLine());
                }
            }

            string betaFilePath = fileB;

            StringBuilder sb = new StringBuilder();


            using (FileStream fs = new FileStream(betaFilePath, FileMode.Open))
            using (StreamReader rdr = new StreamReader(fs))
            {
                while(! rdr.EndOfStream)
                {
                    string[] betaFileLine = rdr.ReadLine().Split(Convert.ToChar(","));

                    if (alphaFileContent.Contains(betaFileLine[0]))
                    {
                        sb.AppendLine(String.Format("{0}", betaFileLine[0]));
                    }
                }
            }

using (FileStream fs = new FileStream(fileC, FileMode.Create))
        using (StreamWriter writer = new StreamWriter(fs))
        {
            writer.Write(sb.ToString());
        }
    }

            //End
        }

推荐答案

String directory = @"C:Whatever";
String[] linesA = File.ReadAllLines(Path.Combine(directory, "FileA-Database.txt"));
String[] linesB = File.ReadAllLines(Path.Combine(directory, "FileB-Database.txt"));

IEnumerable<String> onlyB = linesB.Except(linesA);

File.WriteAllLines(Path.Combine(directory, "Result.txt"), onlyB);

这篇关于逐行比较两个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆