如何在不阅读newline/return的情况下比较2个文件。注意:如果要测试此代码,请在数组目录中的文件中使用许多空格/字符串。示例
这是当前场景
File 1|File2
--- | ---
line1 Hello1|Hello4
line2 Hello1|Hello1
line3 |
line4 Hello2|Hello2
输出将放在另一个文本文件上。
Expected Output :
FROM File2. Line 1 : Hello4
Current Output:
FROM File2. Line 1 : Hello4
FROM File2. Line 3 :
代码:
for (int ctr = 0; ctr <= arrayrows - 1; ctr++)
{
for (int ctr2 = 0; ctr2 <= arraycolumns - 1; ctr2++)
{
if (File.Exists(path + @stringArray[ctr, ctr2]))
{
string[] File1Lines = File.ReadAllLines(path + @stringArray[ctr, ctr2]);
string[] File2Lines = File.ReadAllLines(path + @stringArray2[ctr, ctr2]);
List<string> NewLines = new List<string>();
if (File1Lines.Length >= File2Lines.Length)
{
greaterindex = File1Lines.Length;
}
else if (File2Lines.Length >= File1Lines.Length)
{
greaterindex = File2Lines.Length;
}
for (int lineNo = 0; lineNo <= greaterindex - 1; lineNo++)
{
if (lineNo > (File2Lines.Length - 1))
{
NewLines.Add("FROM File1. Line " + lineNo + ": " + File1Lines[lineNo]);
}
else if (lineNo > (File1Lines.Length - 1))
{
NewLines.Add("FROM File2. Line " + lineNo + ": " + File2Lines[lineNo]);
}
else
{
if (!String.IsNullOrEmpty(File1Lines[lineNo]) && !String.IsNullOrEmpty(File2Lines[lineNo])) //kapag ung same line sa 2 files hindi null
{
if (String.Compare(File1Lines[lineNo], File2Lines[lineNo]) != 0)
NewLines.Add("FROM File2. Line " + lineNo + ": " + File2Lines[lineNo]);
}
else if (!String.IsNullOrEmpty(File1Lines[lineNo])) //kapag ung particular line sa file 2 null
{
}
else //kapag ung particular line sa file 1 null
{
NewLines.Add("FROM File2. Line " + lineNo + ": " + File2Lines[lineNo]);
/*NewLines.Add("==========Discrep Found========");
NewLines.Add("FROM File2: " + File2Lines[lineNo]);
NewLines.Add("FROM File1: " + File1Lines[lineNo]);
NewLines.Add("===============================");*/
}
}
}
尝试使用代码的这一部分而不是(大else
块):
if (!String.IsNullOrWhiteSpace(File1Lines[lineNo]) &&
!String.IsNullOrWhiteSpace(File2Lines[lineNo]))
{
if (String.Compare(File1Lines[lineNo], File2Lines[lineNo]) != 0)
{
NewLines.Add("FROM File2. Line " + lineNo + ": " + File2Lines[lineNo]);
continue;
}
}
else if (!String.IsNullOrWhiteSpace(File1Lines[lineNo]))
{
NewLines.Add("FROM File1. Line " + lineNo + ": " + File2Lines[lineNo]);
continue;
}
else if (!String.IsNullOrWhiteSpace(File2Lines[lineNo]))
{
NewLines.Add("FROM File2. Line " + lineNo + ": " + File2Lines[lineNo]);
continue;
}
使用继续语句和string.isnullorwhitespace方法和卷曲括号并编写所有条件。