您可以创建简单的类来保存必要的数据。在这个类中,我们存储每个文件中的行并Color
指示是否相等。
public class LineComparer
{
public string Line1 { get; set; }
public string Line2 { get; set; }
public Brush Color { get; set; }
}
在下一步中,您必须使用文件中的数据填充列表:
public List<LineComparer> _comparer = new List<LineComparer>();
public void ReadFiles()
{
TextReader tr1 = new StreamReader("file1.txt");
TextReader tr2 = new StreamReader("file2.txt");
string line1, line2 = null;
while ((line1 = tr1.ReadLine()) != null)
{
_comparer.Add(new LineComparer{ Line1 = line1 });
}
int index = 0;
while ((line2 = tr2.ReadLine()) != null)
{
if(index < _comparer.Count)
_comparer[index].Line2 = line2;
else
_comparer.Add(new LineComparer{ Line2 = line2 });
index++;
}
tr1.Close();
tr2.Close();
_comparer.ForEach(x => { if(x.Line1 != x.Line2) x.Color = new SolidColorBrush(Colors.Red); else x.Color = new SolidColorBrush(Colors.Green); });
}
要显示文件差异,您可以ListBox
使用ItemTemplate
:
<ListBox ItemsSource="{Binding}"
Grid.IsSharedSizeScope="True"
>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="{Binding Color}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" SharedSizeGroup="A" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" SharedSizeGroup="B" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Line1}"
TextWrapping="Wrap" />
<TextBlock Text="{Binding Line2}"
TextWrapping="Wrap"
Grid.Column="2"
/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
例子:
“file1.txt”:
First
Second
Third
Fourth
Fifth
Sixth
Seventh
“文件2.txt”:
First
second
Third
Fourth
Fifth
结果是:
这是示例解决方案(FileComparer.zip)。