2
votes

New to using isolated storage on windows phone.

I want to save some information in a xml file using isolated storage in my windows phone application. I was just wondering, if the user or the app exists while I'm writing to the xml file, I'll probably end up with some data corruption? Is this the case? If so, how do I protect against this?

1

1 Answers

1
votes

Pretty much every kind of file can be corrupted during a write operation on most filesystems/operating systems - worst case, you have a large file that takes a couple of seconds to write to disk, and the battery falls out while saving it. So my answer is not specific to Windows Phone.

A common workaround is to create a temporary file and then replace/rename it. Renaming a file is an atomic operation, meaning it either happens or it doesn't happen - nothing in between.

So the following pseudocode will be safe:

SaveFile(filename))
    SaveNewFile(stream, filename + ".new.tmp")
    TryDeleteFile(filename + ".old.tmp")
    RenameFile(filename, filename + ".old.tmp")
    RenameFile(filename + ".new.tmp", filename)
    DeleteFile(filename + ".old.tmp")

LoadFile(filename)
    TryRenameFile(filename + ".old.tmp", filename)
    OpenFile(filename)

This is simpler if a replace operation is available:

SaveFile(filename)
    SaveNewFile(stream, filename + ".new.tmp")
    ReplaceFile(filename, filename + ".new.tmp")

LoadFile(filename)
    OpenFile(filename)

It does get trickier if multiple processes access the same files because then you need to lock the files to cover edge cases. A far simpler way to avoid corruption is to use a database, like the following:

http://msdn.microsoft.com/en-US/library/windowsphone/develop/hh202860(v=vs.105).aspx

Databases do not avoid this problem, they solve it. They still use files behind the scenes and do contain all the logic to do something similar to the pseudocode above, including locking schemes to avoid all the edge cases.