views:

278

answers:

4

I'm looking for a way to detect file corruption using C#. Maybe this is too vague, but I'm not looking for specific types of corruption, just wondering if there's a way to detect that a file has been corrupted in general. Anyone know if this is possible and if so how you'd do it in C#? Thanks.

+5  A: 

If you know what the file is supposed to look like, you could compare it against a known good MD5 hash.

Aside from that, if you're looking for specific patterns of corruption. For example, a sequence of bytes should be at some location, but it gets messed up, that could be a flag. it all depends on what specifically you are looking for.

Joel Martinez
+4  A: 

The common method is to use something like CRC. You compare the CRC contained within the file (normally appended to the file) with the CRC calculated from the payload. If they don't match, you know the data is corrupt.

Charlie Salts
+1  A: 

There's no API that'll enable you to detect file corruption. You'll have to do it yourself, and how you'd do that depends entierly on your needs.

nos
A: 

File systems generally don't do this. As far as I know there are three reasons.

First, any kind of anti-corruption algorithm is going to involve checksums of some type, which are a little expensive computationally.

Second, there are at least two causes of corruption. Files could be corrupted when a drive sector goes bad, but they could also be corrupted by an application. And of course, when that application modifies the file and saves it's new version, it's always going to say that the new version is great even if it replaced every other word with 'poop'.

Third, what can you do other than throw an exception when a file is corrupt? If you're checksuming the file then you have a cleaner way to know that the file's broken, but in the end it's still broken, and not much that you can do except halt.

quillbreaker