5

If I have a file that I want to monitor for any changes (other than looking at the file date stamps etc).

How could I perform a SHA1 hash on its contents?

I think this is what GIT does, so I just want to learn how to do it

4
  • 3
    Is there a reason why you wouldn't just use a FileSystemWatcher? msdn.microsoft.com/en-us/library/… Commented Dec 28, 2009 at 15:29
  • 2
    Because it doesn't work, of course. Only on some supported file systems. Commented Dec 28, 2009 at 15:42
  • @Will Even on supported file systems, it is not guaranteed to fire (limited buffer size). Commented Mar 13, 2017 at 15:20
  • @vossad01 unfortunate, but true. Commented Mar 13, 2017 at 15:25

2 Answers 2

23
using (FileStream stream = File.OpenRead(@"C:\File.ext")) { using (SHA1Managed sha = new SHA1Managed()) { byte[] checksum = sha.ComputeHash(stream); string sendCheckSum = BitConverter.ToString(checksum) .Replace("-", string.Empty); } } 

Calculate the checksum periodically.

Sign up to request clarification or add additional context in comments.

2 Comments

That's a file, he asked about a directory.
His question says "If I have a file that I want to monitor for any changes" , I read "File" , where do you see Directory?
0

For the specific application that you described, finding the SHA-1 hash of each file in the directory and then XORing them together would work well.

byte[] checksum = new byte[sha1Length]; for each file for (int index = 0; index < sha1Length; index++) checksum[index] ^= fileChecksum[index] 

Edited to Add: As pointed out in the comments, this won't really work. One specific scenerio would be adding two identical files, which would cancel each other out in the XOR. Perhaps creating a stream with all the file names and timestamps and file hashes and then hashing that would give you what you need.

Edited again: OK, now you've changed your question! So nevermind!

1 Comment

xor isn't really advisable if security is a concern (he doesn't say it is, but maybe...). Instead I'd suggest sorting the files and hashing the hashes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.