Compare Files Method in C# Unit Testing

I’ve been working on a class that wraps the low-level PGP crypto capabilities of Bouncy Castle and presents a higher-level, directly-usable interface similar to a command-line utility. One obvious test is to start with a file, sign and encrypt it, then decrypt it, and compare the result with the original. I’ve gotten so spoiled to having so many rudimentary things like this already available in the .net framework I was surprised when I didn’t find a Compare method on the File class or anything like it somewhere else. If there is something already built-in, please post a comment. If there isn’t, hopefully this small method will save a few people a few minutes.

private bool FileCompare(string srcFileName, string dstFileName)
{
const int BUFFER_SIZE = 1 << 16; FileInfo src = new FileInfo(srcFileName); FileInfo dst = new FileInfo(dstFileName); if ( src.Length != dst.Length ) return false; using ( Stream srcStream = src.OpenRead(), dstStream = dst.OpenRead() ) { byte[] srcBuf = new byte[BUFFER_SIZE]; byte[] dstBuf = new byte[BUFFER_SIZE]; int len; while ((len = srcStream.Read(srcBuf, 0, srcBuf.Length)) > 0)
{
dstStream.Read(dstBuf, 0, dstBuf.Length);
for ( int i = 0; i < len; i++) if ( srcBuf[i] != dstBuf[i]) return false; } return true; } } [/sourcecode]

Advertisements

3 Responses to “Compare Files Method in C# Unit Testing”

  1. Richard Sudworth Says:

    I was interested to read that like me, you are using the Bouncy Castle PGP code. You mention that you are signing and then encrypting a file: have you got that to work? I’m really having trouble doing both actions. Would you be able to give me any advice?

    Thanks and I hope you can help,

    Richard.

  2. jopincar Says:

    Richard, I was very disappointed in the built-in functionality with BC PGP. In most real-world scenarios, you have to sign and encrypt in one pass but they do not include any examples or built-in support for it. I was able to get something working with a lot of effort. I am going to do a post with the code to demo this.

  3. Richard Sudworth Says:

    Great, I’ll look forward to reading how you did it.

    I think I have got together something based on discussions about the Java version in the BC mailing list archive. I’m interested to see if your solution went down the same path as mine as it seems pretty convoluted.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: