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

3

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

Ex: I have a "xpto.txt" file in a directory and need to verify that the file is not corrupted.

    
asked by anonymous 14.05.2015 / 22:36

1 answer

1

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

Example usage:

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 removed it from . This method only works if you have the CRC of an intact 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 this opening raises any exceptions, but this does not necessarily check whether the file is corrupted or not: it checks only whether it can be read or not, which is something else :

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

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

The latter I removed from here .

    
15.05.2015 / 00:26