Roberto Bonini
Roberto Bonini

Reputation: 7303

Avoiding File Corruption due to Power Outages

I'm writing a simple application in .Net C# that will upload ZIP files to a central server for processing.

However, the environment that this application will be use it is susceptible to frequent power outages.

I'm currently reading the file in using File.ReadAllBytes and uploading by passing the resulting byte array to WebClient.UploadData.

Assuming that a power outage interrupts the call to ReadAllBytes, could file corruption occur and how best to deal with that possibility?

Thanks,

Roberto

Upvotes: 3

Views: 1350

Answers (1)

usr
usr

Reputation: 171178

If a power outage interrupts the reading, of course the reading will be aborted. I do not understand this part of the question. You should be concerned about writing.

Two kinds of writes can go wrong here:

  1. Writing the ZIP to disk. If interrupted you get a partial file. You can make this safe by first writing the ZIP to a temp file and then renaming it only once it is complete. You also must insert a Flush before renaming. Renaming is atomic and crash-safe on NTFS.
  2. Writing to the server over the network. You can make that safe by first submitting the expected file length (or hash). The server must validate that length to make sure transmission completed.

If any kind of error is detected using these methods you need to restart the process.

Upvotes: 2

Related Questions