C# - Comparing two CSV Files and giving an output

后端 未结 3 522
栀梦
栀梦 2021-01-15 19:29

Need a bit of help, I have two sources of information and the information is exported to two different CSV file\'s by different programs. They are supposed to include the sa

3条回答
  •  借酒劲吻你
    2021-01-15 20:32

    Assuming that the files are really supposed to be identical, right down to text qualifiers, ordering of rows, and number of rows contained in each file, the simplest approach may be to simply iterate through both files together and compare each line.

    using (StreamReader f1 = new StreamReader(path1))
    using (StreamReader f2 = new StreamReader(path2)) {
    
        var differences = new List();
    
        int lineNumber = 0;
    
        while (!f1.EndOfStream) {
            if (f2.EndOfStream) {
               differences.Add("Differing number of lines - f2 has less.");
               break;
            }
    
            lineNumber++;
            var line1 = f1.ReadLine();
            var line2 = f2.ReadLine();
    
            if (line1 != line2) {
               differences.Add(string.Format("Line {0} differs. File 1: {1}, File 2: {2}", lineNumber, line1, line2);
            }
        }
    
        if (!f2.EndOfStream) {
             differences.Add("Differing number of lines - f1 has less.");
        }
    }
    

提交回复
热议问题