比较csv文件中的行

时间:2017-12-19 13:09:34

标签: c# csv

我目前正在使用以下代码来比较两个csv文件。此代码提供的输出包含所有不相同的行。但是当一行丢失后,该行之后的所有内容都不一样。我怎样才能解决这个问题?提前谢谢。

List<string> lines = new List<string>();
List<string> lines2 = new List<string>();

try
{
    StreamReader reader = new StreamReader(System.IO.File.OpenRead(file1));
    StreamReader read = new StreamReader(System.IO.File.OpenRead(file2));
    List<string> differences = new List<string>();
    string line;
    string line2;

    int i = 0;
    while ((line = reader.ReadLine()) != null && (line2 = read.ReadLine()) != null)
    {
        string[] split = line.Split(Convert.ToChar("\t"));
        string[] split2 = line2.Split(Convert.ToChar("\t"));

        if (split[i] != split2[i])
        {
            differences.Add("this row is not the same:, " + line);
        }
        else
        {
        }
        i++;
    }
    System.IO.File.WriteAllLines(differencesFile, differences);
    reader.Dispose();
    read.Dispose();
}
catch
{
}

1 个答案:

答案 0 :(得分:0)

在朋友的帮助下,我使用了这段代码:

 List<string> file1 = new List<string>();
        List<string> output = new List<string>();
        string differencesFile = path;
        File.WriteAllText(differencesFile, "");
        try
        {
            StreamReader readFile1 = new StreamReader(System.IO.File.OpenRead(pathfile1));

            string lineFile1;
            while ((lineFile1 = readFile1.ReadLine()) != null)
            {
                bool match = false;
                string[] colums = lineFile1.Split('\t');

                StreamReader readFile2 = new StreamReader(System.IO.File.OpenRead(pathfile2));
                string line2;
                while ((line2 = readFile2.ReadLine()) != null)
                {
                    string[] columsFile2 = line2.Split('\t');
                    if (colums[0] == columsFile2[0])
                    {
                        match = true;
                    }
                }
                if (!match)
                {

                    output.Add(colums[0] + "; doesnt exist in pathfile2");


                }
            }
            System.IO.File.WriteAllLines(differencesFile, output);

        }
        catch { }
相关问题