Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert statement to compare two files for equality

I am writing from one file to another and i created an Assert statement in my tests to check and see if the new file equals the original file but was not sure what is the best way to go about it. I tried Assert.Equals but it returned as failed even though i physically checked both files and they are exactly the same.

 Assert.IsTrue(File.Equals(downloadfile, created), "Files do not match");
like image 357
Masriyah Avatar asked Oct 18 '25 18:10

Masriyah


1 Answers

Create an MD5 or SHA hash of the files, and compare those.

public string GetFileHash(string filename)
{
    var hash = new SHA1Managed();
    var clearBytes = File.ReadAllBytes(filename);
    var hashedBytes = hash.ComputeHash(clearBytes);
    return ConvertBytesToHex(hashedBytes);
}

public string ConvertBytesToHex(byte[] bytes)
{
    var sb = new StringBuilder();

    for(var i=0; i<bytes.Length; i++)
    {
        sb.Append(bytes[i].ToString("x"));
    }
    return sb.ToString();
}

[Test]
public void CompareTwoFiles()
{
    const string originalFile = @"path_to_file";
    const string copiedFile = @"path_to_file";

    var originalHash = GetFileHash(originalFile);
    var copiedHash = GetFileHash(copiedFile);

    Assert.AreEqual(copiedHash, originalHash);
}
like image 98
Jedediah Avatar answered Oct 20 '25 06:10

Jedediah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!