tags:

views:

129

answers:

3

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

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

            }

Calculate the checksum periodically.

RandomNoob
That's a file, he asked about a directory.
Will
His question says "If I have a file that I want to monitor for any changes" , I read "File" , where do you see Directory?
RandomNoob
It's in the title. The question is unclear.
Samir Talwar
sorry, fixed that.
mrblah
+1  A: 

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!

Jeffrey L Whitledge
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.
Kevin Montrose
@Kevin Montrose - Indeed, I'll edit the answer.
Jeffrey L Whitledge
A: 

Slowly. Any particular reason why it should be a secure hash?

Stephan Eggermont
this should be a comment, not an answer
Rubens Farias
No, it should not. No programming language mentioned, so the other answers are worse. And the real problem is with the question, not the answer
Stephan Eggermont