比较C#中的两个文件

Toz*_*Toz 15 .net c# compare file

我想比较C#中的两个文件,看看它们是否不同.它们具有相同的文件名,并且在不同时它们的大小完全相同.我只是想知道是否有一种快速的方法来做到这一点,而无需手动进入并读取文件.

谢谢

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)

  • 代码是正确的,但您必须向下滚动才能看到进行逐字节比较的位.我假设丹尼尔没有向下滚动. (11认同)
  • @Daniel:抱歉复活旧帖子,但你能解释一下代码的实际问题是什么吗?对我来说似乎没关系,它正在检查文件大小然后逐字节.单个角色的差异如何逃脱检查?格拉西亚斯! (4认同)
  • 使用更多`使用'! (4认同)
  • 这实际上是从微软的网站提取的。它执行相等比较,长度比较和逐字节比较。我认为您可能对此不对。 (2认同)

jas*_*son 18

我只是想知道是否有一种快速的方法来做到这一点,而无需手动进入并读取文件.

并不是的.

如果文件带有哈希值,你可以比较哈希值,如果它们不同,你可以得出结论文件是不同的(但是,相同的哈希值并不意味着文件是相同的,所以你仍然需要通过字节比较).

但是,哈希使用文件中的所有字节,因此无论如何,您在某些时候都必须以字节为单位读取文件.事实上,只需逐个字节比较就可以比计算哈希更快.这是因为哈希读取所有字节就像逐字节比较一样,但哈希做了一些其他计算,增加了时间.另外,逐字节比较可以在第一对非相等字节的早期终止.

最后,您无法避免需要逐字节读取.如果哈希值相等,那并不意味着文件是相等的.在这种情况下,您仍然需要逐字节进行比较.

  • Downvoter:解释一下. (3认同)
  • 如果您有相同的哈希值,则可以确定文件是相同的.你是正确的,你需要逐字节比较文件,以确保绝对(特别是如果您的安全依赖于此).但是像git这样的系统依赖于两个具有相同散列的不同文件不会出现在系统内部的事实.当然,这都假设好散列,而不是像'GetHashCode()`. (2认同)
  • @scottm:因为不相等的文件可以有相等的哈希值.这是鸽子原则.假设我们正在使用md5.md5生成128位的文件哈希值.因此,有2 ^ 128个不同的哈希值.有超过2 ^ 128个不同文件的方式.因此,由于我们将具有2 ^ 128个不同值的空间映射到具有2 ^ 128个值的空间,因此必须存在冲突.哈希不是唯一的签名. (2认同)