Question

I am creating a WPF/C# app that deletes files and creates new ones before closing (from online data). The problem comes when the app randomly crashes before the new file creation process is complete or even starts.

Is there a way of file recovery (to be done within the app not just undelete apps etc) that I can use in my code so when the app crashes the file that was deleted cannot be lost?

To be more accurate I delete the 4 files at the start of the app and create new ones at the end of the app. But if the app crashes in the middle the files are lost.

How can I prevent this issue?

I tried to reduce the probability of random crashing but once in a while it still happens.

Était-ce utile?

La solution

If you're warry about lost of the file(s), you can:

  • before deleting of A.txt (say) on startup create it's copy A.tmp and after delete.
  • on close, create new files and delete all tmp file(s) present in directory.

In this way, if something went wrong during program run, when program starts again, it will find tmp last created, so can reconstruct information (if need) from them and continue program cycle.

Autres conseils

On startup, do nothing to the files.

On shutdown, follow this procedure:

  1. Create the new files, named OLDNAME.tmp or something. If it exists already, discard and recreate it.
  2. Rename the new files over the old ones via MoveFileTransacted() (MSDN)

If you are stuck on an old version of Windows without MoveFileTransacted(), things get more complicated: http://blogs.msdn.com/b/adioltean/archive/2005/12/28/507866.aspx


Note: Should you find yourself on a POSIX compliant filesystem, the standard rename operation is guaranteed to be atomic, making step 2 trivial.

Consider moving the files to some temporary folder, rather than deleting them. You can invent some undeleting technique, however this will not be reliable as the file system can rewrite unoccupied space anytime. After the new files arrived, you would delete the previously moved files.

Don't delete the old files until the new ones are created? Rename them out the way instead. When you start the app you'll know if it crashed since the old (renamed) files will still be there and you can perform any tidy up operations then.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top