How to check if a file is corrupted in c#?


How to check if a file is corrupted in c#?

Ex: I have a file "xpto.txt" in a directory and I need to check if this file is not corrupted.


One option is checking the CRC. There is a library called DamienGKit that implements Crc32 .

Example of use:

Crc32 crc32 = new Crc32();

String hash = String.Empty;

using (FileStream fs = File.Open("c:\\meuarquivo.txt", FileMode.Open))
  foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();

Console.WriteLine("CRC-32 é {0}", hash);

I took it from here . This method only works if you have the CRC of a healthy file. If they are different (the original and copy CRC) for the same modification date, the file is corrupted.

Another way is to try to open the file as read-only and check if that opening raises any exceptions, but that doesn't necessarily check whether the file is corrupt or not: it just checks whether it is readable or not, which is something else:

var fi = new System.IO.FileInfo(@"C:\meuarquivo.txt");

  if (fi.IsReadOnly)
    // Se entrar aqui, o arquivo está ok.
catch (Exception ex)
  Response.Write("Problema ao ler arquivo.");

This last one I took from here .

Scroll to Top