c# - C#比较两个文件

标签 c# .net file compare

<分区>

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

谢谢

最佳答案

根据您希望走多远,您可以查看 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);
}

关于c# - C#比较两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7931304/

相关文章:

c# - 什么是 C# 等同于 VB6 的 Label.FontName?

.net - 哪里是开始学习LINQ的好地方

python 2.7 : how to read only a few lines at a time from a file?

python - 使用 glob 排除子文件夹

c# - CheckedListBox 选择所有项目 - Windows 窗体 C#

c# - Facebook DotNetOpenAuth 收到意外的 OAuth 授权响应

c# - 如何在单声道(GTK)中更改窗口背景颜色?

.net - F# 中的函数应用运算符 ($)?

c# - 在带有复选框的GridView中显示存储过程的结果

java - 从java中的不同类写入同一个文件