简体   繁体   English

比较两个文本文件是否相同 C#

[英]Comparing that two text files are identical C#

I'm trying to compare two text files and check if they are identical otherwise I'll be returning false .我正在尝试比较两个文本文件并检查它们是否相同,否则我将返回false

The two text files I'm comparing are identical but the result bool is false .我比较的两个文本文件是相同的,但结果 bool 是false

StreamReader sr1 = new StreamReader(@"..\..\..\Test\expected_result_1.txt");                        
StreamReader sr2 = new StreamReader(@"\temp_dir\result01.txt");
result = compareFiles(ref sr1,ref sr2);

And here I have the function:在这里我有 function:

public bool compareFiles(ref StreamReader file1, ref StreamReader file2)
{
    bool result = true;
    while (!file1.EndOfStream)
    {
        if (file1.Read() != file2.Read())
        {
            result = false;
            break;
        }
    }
    if (result)
    {
        if (!file2.EndOfStream)
        {
            result = false;
        }  
    }
    return result;
} 

Update: The two text files are identical so I compared them in a hex editor and the hex dump was slightly different.更新:这两个文本文件是相同的,所以我在十六进制编辑器中比较了它们,十六进制转储略有不同。 What should be done when encountering this issue?遇到这个问题应该怎么办?

You can simplify your code.您可以简化代码。

public bool compareFiles(ref StreamReader file1, ref StreamReader file2)
{
  try 
  {
    //Must put that check in a try/catch block, because not every stream
    //supports checking the length.
    if (file1.BaseStream.Length != file2.BaseStream.Length)
      return false;
  } catch {}  //but can safely ignore the exception 

  while (!file1.EndOfStream)
  {
    //once you read different chars from stream, you can return
    if (file1.Read() != file2.Read())
      return false;
  }
  //if you read file1 to the end, file2 must also be at the end 
  return file2.EndOfStream;
}

But in prinicple your code should work too.但原则上,您的代码也应该可以工作。 Maybe you have a linebreak in the end of one file, or some trailing whitespaces, ... Have you tried passing the same file in for both parameters?也许您在一个文件的末尾有一个换行符,或者一些尾随空格,......您是否尝试过为两个参数传递同一个文件? It should return true.它应该返回 true。

If the files are small, and if they are text files, which you say they are, then instead of streaming there are higher level methods for file handling.如果文件很小,并且它们是文本文件,如您所说的那样,那么除了流式传输之外,还有用于文件处理的更高级别的方法。 For example:例如:

File.ReadAllText(f1) == File.ReadAllText(f2)

That will compare the contents of 2 files in 1 line without worrying about is 1 stream longer than the other etc.这将比较 1 行中 2 个文件的内容,而不必担心 1 stream 比其他文件长,等等。

Of course it is slower this way, but for 1kb you won't notice.当然,这种方式速度较慢,但对于 1kb,您不会注意到。

Another pointer, check if you really need to pass variables to a method using 'ref'.另一个指针,检查您是否真的需要使用“ref”将变量传递给方法。 That is not required in the code above.这在上面的代码中不是必需的。 Maybe read up on that.也许阅读一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM