如何在C#中检测两个文件是否完全相同(大小、内容等)?
发布于 2008-10-17 04:04:26
这里有一个简单的解决方案,它只读取两个文件并比较数据。它不应该比hash方法慢,因为这两种方法都必须读取整个文件。正如其他人所指出的,由于它的简单性,这种实现实际上比散列方法慢一些。有关更快的方法,请参阅以下内容。
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方法需要的实际计算就会减少。无论如何,我在最初的实现中复制了您的性能观察结果,但是当我添加一些简单的缓冲时,compare-all-bytes方法也同样快。下面是缓冲实现,欢迎进一步评论!
hash EDIT Jon B提出了另一个优点:在文件实际上不同的情况下,此方法可以在找到第一个不同的字节时立即停止,而方法在任何情况下都必须读取两个文件的整个。
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;
}发布于 2008-10-17 04:01:51
或者您可以逐个字节地比较这两个文件。
https://stackoverflow.com/questions/211008
复制相似问题