0

I want to check a file is corrupt or not before copying to another file which is actually a backup of 1st one and will be restored if something goes wrong with original file.

System.IO.File.Copy(FileA, FileB, true);

Sometimes my original file get corrupted and as i have no check for corruption while copying i also corrupt my backup file.

Any help will be appreciated.

Thanks,

  • Is it being corrupted because of the copy, or prior to? If it happens during the copy, then Oshant's solution should work; just get a hash before & after the copy to make sure they're the same. – sab669 Oct 13 '15 at 16:15
  • It got corrupted before copy(Due to some reason). So now when I am tacking backup, my backup file is also corrupted. I don't want to copy if my original file is corrupt after that I will restore my original file by just copying the content of backup file to original one. –  Oct 14 '15 at 05:24
  • Are you sure the file you're trying is closed and you have no instance of any use it? – Oshant Oct 14 '15 at 11:50
  • My application change the content of xml every time. and every time after writing the data in xml i take the same data in backup file,So i can restore the data in original file if something goes wrong with original file.The original file is only modified by single process and stream is closed properly. Now i am trying to serialize the xml and it give exception and i handle things in catch.That exception indicates that something is wrong with file. Computing the hash was good idea,but in my case content of file is keep changing so i can't use it.....But thank you very much. –  Oct 14 '15 at 17:28

1 Answers1

1

You can check with MD5

    using (var md5 = MD5.Create())
{
    using (var stream = File.OpenRead(filename))
    {
        return md5.ComputeHash(stream);
    }
}

font: Calculate MD5 checksum for a file

Community
  • 1
  • 1
Oshant
  • 159
  • 1
  • 17