我在C#中有2个文本文件说:File - A
& File - B
。我想要比较两个文件内容,如果File - A
中找不到File - B
中没有的任何内容,那么我想将该内容放在文件-B中,位于File - A
的同一位置{1}}。
File - A File - B
This is the example text. This is text.
现在,如果我们比较2个以上的文件内容,那么输出应为:
File - B
This is the example text.
那么,如果c#中有任何方法可以为我做这个,请告诉我吗?
答案 0 :(得分:2)
var f1 = File.ReadAllLines(@"c:\temp\l1.txt");
var f2 = File.ReadAllLines(@"c:\temp\l3.txt");
var result = f1.Select((l, index) => new {Number= index, Text = l})
.Join(f2.Select((l, index) => new {Number= index, Text = l}),
inner => inner.Number,
outer => outer.Number,
(inner, outer) => {
if(inner.Text == "")
return outer.Text;
return inner.Text;
})
.Concat(f1.Where((l, index) => index >= f2.Count()))
.Concat(f2.Where((l, index) => index >= f1.Count()));
//.Dump();
File.WriteAllLines(@"c:\temp\l3.txt", result);
这将逐行比较,如果第一个文件的行为空,将保留seconde文件的行,否则总是打印第一个文件行....
然后我们用两个文件左边的行结束结果。
答案 1 :(得分:1)
我真的没有完整的要求,但在这里。
string[] fileAWords = File.ReadAllText("C:\\File - A.txt").Split(' ');
string[] fileBWords = File.ReadAllText("C:\\File - B.txt").Split(' ');
// The comparer makes it so the union is case insensitive
// For example: Welcome in File - A and welcome (lower-case) in File - B in a Union would both be in the result
// With the comparer, it will only appear once.
IEnumerable<string> allWords = fileAWords.Union(fileBWords, new StringEqualityComparer());
// We did the split on a space, so we want to put the space back in when we join.
File.WriteAllText("C:\\File - C.txt", string.Join(" ", allWords));
StringEqualityComparer类代码是:
class StringEqualityComparer : IEqualityComparer<string>
{
// Lower-case your strings for a case insensitive compare.
public bool Equals(string s1, string s2)
{
if (s1.ToLower().Equals(s2.ToLower()))
{
return true;
}
else
{
return false;
}
}
#region IEqualityComparer<string> Members
public int GetHashCode(string s)
{
return s.GetHashCode();
}
#endregion
}
答案 2 :(得分:1)
试试这个:
string fileAContent = File.ReadAllText(fileAPath);
string fileBContent = File.ReadAllText(fileBPath);
string[] fileAWords = filesAContent.split(_your delimiters_);
string[] fileBWords = filesBContent.split(_your delimiters_);
if (fileAWords.Except(fileBWords).Length > 0)
{
// there are words in file B that are not in file A
}
如果要优化性能,可以在HashSet中添加fileAWords中的所有单词,然后迭代所有fileBWords并检查hashset中是否存在不存在的工作
答案 3 :(得分:1)
简单的LINQ方法:
var file1 = File.ReadLines(path1);
var file2 = File.ReadAllLines(path2);
var onlyInFileA = file1.Except(file2);
File.WriteAllLines(path2, file2.Concat(onlyInFileA));
答案 4 :(得分:-2)
您可以使用File.ReadAllLines方法。