Anyname Donotcare
Anyname Donotcare

Reputation: 11393

How to know if the uploaded file has been changed?

If the user uploads some file to my server and I want to make sure that the file hasn't been changed from the last time the user uploaded it, how can I get this information?

I have a log table with User_id and FileName (the User_id is unique). I delete the file after I read the contents.

Upvotes: 3

Views: 928

Answers (2)

Massimo
Massimo

Reputation: 3460

Hash is the generic kind of function. Usually to detect changes into large chunks of data, like files, is used some crc

Under linux there is the standard utility cksum

You can spawn a cksum filename and grab the output. Store it, for example in your database, and check on new file incoming.

Upvotes: 3

driis
driis

Reputation: 164291

You can store a hash of the file before deleting it. To see if it is the same file being uploaded, compare the hash with the previous hash. You can do this with one of the HashAlgorithm classes in System.Cryptography, such as SHA1.

"A cryptographic hash function is a deterministic procedure that takes an arbitrary block of data and returns a fixed-size bit string, the (cryptographic) hash value, such that an accidental or intentional change to the data will change the hash value"

Here is some example code to get you started, assuming the variable stream is a stream with your file data (you could use FileStream to open it):

var sha = new System.Security.Cryptography.SHA1Managed();
byte [] hash = sha.ComputeHash(stream);

Now, the variable hash will contain the hash, a fingerprint of the file contents. Even a small change (such as a single bit) will result in a different hash value, but taking the hash on the same file will always return the same hash.

Upvotes: 7

Related Questions