简体   繁体   中英

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 .

The two text files I'm comparing are identical but the result bool is 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:

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.

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.

Of course it is slower this way, but for 1kb you won't notice.

Another pointer, check if you really need to pass variables to a method using 'ref'. That is not required in the code above. Maybe read up on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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