3
How to check if a file is corrupted in c#?
Ex: I have a "xpto.txt" file in a directory and need to check that this file is not corrupted.
3
How to check if a file is corrupted in c#?
Ex: I have a "xpto.txt" file in a directory and need to check that this file is not corrupted.
1
One option is to check 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 an intact file. If they are different (the original and copy CRC) for the same modification date, the file is corrupted.
Another way is trying to open the file as read-only and check whether this opening raises any exceptions, but it doesn’t necessarily check whether the file is corrupted or not: just checks 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.");
}
Browser other questions tagged c# filing-cabinet
You are not signed in. Login or sign up in order to post.
Do you have any checksum of the original file, so that it can be checked and compared?
– Fernando Leal