Jam*_*son 28
根据你想要的程度,你可以看看Diff.NET
这是一个简单的文件比较功能:
// This method accepts two strings the represent two files to
// compare. A return value of 0 indicates that the contents of the files
// are the same. A return value of any other value indicates that the
// files are not the same.
private bool FileCompare(string file1, string file2)
{
int file1byte;
int file2byte;
FileStream fs1;
FileStream fs2;
// Determine if the same file was referenced two times.
if (file1 == file2)
{
// Return true to indicate that the files are the same.
return true;
}
// Open the two files.
fs1 = new FileStream(file1, FileMode.Open, FileAccess.Read);
fs2 = new FileStream(file2, FileMode.Open, FileAccess.Read);
// Check the file sizes. If they are not the same, the files
// are not the same.
if (fs1.Length != fs2.Length)
{
// Close the file
fs1.Close();
fs2.Close();
// Return false to indicate files are different
return false;
}
// Read and compare a byte from each file until either a
// non-matching set of bytes is found or until the end of
// file1 is reached.
do
{
// Read one byte from each file.
file1byte = fs1.ReadByte();
file2byte = fs2.ReadByte();
}
while ((file1byte == file2byte) && (file1byte != -1));
// Close the files.
fs1.Close();
fs2.Close();
// Return the success of the comparison. "file1byte" is
// equal to "file2byte" at this point only if the files are
// the same.
return ((file1byte - file2byte) == 0);
}
Run Code Online (Sandbox Code Playgroud)
jas*_*son 18
我只是想知道是否有一种快速的方法来做到这一点,而无需手动进入并读取文件.
并不是的.
如果文件带有哈希值,你可以比较哈希值,如果它们不同,你可以得出结论文件是不同的(但是,相同的哈希值并不意味着文件是相同的,所以你仍然需要通过字节比较).
但是,哈希使用文件中的所有字节,因此无论如何,您在某些时候都必须以字节为单位读取文件.事实上,只需逐个字节比较就可以比计算哈希更快.这是因为哈希读取所有字节就像逐字节比较一样,但哈希做了一些其他计算,增加了时间.另外,逐字节比较可以在第一对非相等字节的早期终止.
最后,您无法避免需要逐字节读取.如果哈希值相等,那并不意味着文件是相等的.在这种情况下,您仍然需要逐字节进行比较.