【发布时间】:2010-09-17 16:22:29
【问题描述】:
如何在 C# 中检测两个文件是否完全相同(大小、内容等)?
【问题讨论】:
标签: c#
如何在 C# 中检测两个文件是否完全相同(大小、内容等)?
【问题讨论】:
标签: c#
或者你可以逐字节比较这两个文件......
【讨论】:
这是一个简单的解决方案,它只读取两个文件并比较数据。它不应该比散列方法慢,因为这两种方法都必须读取整个文件。 编辑 正如其他人所指出的,这种实现实际上比散列方法要慢一些,因为它很简单。请参阅下文了解更快的方法。
static bool FilesAreEqual( string f1, string f2 )
{
// get file length and make sure lengths are identical
long length = new FileInfo( f1 ).Length;
if( length != new FileInfo( f2 ).Length )
return false;
// open both for reading
using( FileStream stream1 = File.OpenRead( f1 ) )
using( FileStream stream2 = File.OpenRead( f2 ) )
{
// compare content for equality
int b1, b2;
while( length-- > 0 )
{
b1 = stream1.ReadByte();
b2 = stream2.ReadByte();
if( b1 != b2 )
return false;
}
}
return true;
}
您可以将其修改为一次读取多个字节,但内部文件流应该已经在缓冲数据,因此即使是这个简单的代码也应该相对较快。
编辑感谢您在此处提供有关速度的反馈。我仍然认为 compare-all-bytes 方法可以和 MD5 方法一样快,因为这两种方法都必须读取整个文件。我怀疑(但不确定)一旦文件被读取,比较所有字节方法需要较少的实际计算。无论如何,我在最初的实现中重复了您对性能的观察,但是当我添加一些简单的缓冲时,compare-all-bytes 方法同样快。下面是缓冲实现,欢迎进一步评论!
EDIT Jon B 提出了另一个好点:在文件实际不同的情况下,此方法可以在找到第一个不同字节时立即停止,而 hash 方法必须读取在每种情况下,这两个文件都是完整的。
static bool FilesAreEqualFaster( string f1, string f2 )
{
// get file length and make sure lengths are identical
long length = new FileInfo( f1 ).Length;
if( length != new FileInfo( f2 ).Length )
return false;
byte[] buf1 = new byte[4096];
byte[] buf2 = new byte[4096];
// open both for reading
using( FileStream stream1 = File.OpenRead( f1 ) )
using( FileStream stream2 = File.OpenRead( f2 ) )
{
// compare content for equality
int b1, b2;
while( length > 0 )
{
// figure out how much to read
int toRead = buf1.Length;
if( toRead > length )
toRead = (int)length;
length -= toRead;
// read a chunk from each and compare
b1 = stream1.Read( buf1, 0, toRead );
b2 = stream2.Read( buf2, 0, toRead );
for( int i = 0; i < toRead; ++i )
if( buf1[i] != buf2[i] )
return false;
}
}
return true;
}
【讨论】: