Transactional open / write / replace in .NET?

I think maybe I should limit it to 8k. I would like to open the file and write from beginning to end every time. However, if for some reason (say, power outage) it does not complete, I do not want corrupted data. Is there a way to make the transaction file open / write / close so that it does not replace the previous file if its success was not successful?

When I google, I get a lot of database transaction results and ado instead of files

+4
source share
3 answers
  • Write to temporary file,
  • Delete old file
  • Rename the new file only if the recording was successful.

To prevent data loss, if you lose power after step two, but before step three, you will need one more step:

  • When starting the program, check for temporary files that have their main files deleted, but have not yet been renamed. If you find anything, follow the third step for these files.
+3
source

NTFS in Windows Vista and later is transactional.

I do not believe that you can access it from pure managed code - you will need P / Invoke in the Win32 API.

A good place to start would be the CreateTransaction , CommitTransaction , RollbackTransaction , CreateFileTransacted (and other *Transacted ) Win32 API functions.

+2
source

A small change in the Mark Byer solution that I use all the time:

  • Enter the new contents in the temp file in the same directory as the file you want to replace.
  • If the recording was successful, rename [1] to the desired file.

Renaming is atomic, so if it succeeds, the system does not remain in an undefined state. If it fails, then, again, the system is still in pristine condition. And you have a backup copy of the content that you would like to replace (in a temporary file) when you reboot the system.

My typical naming convention has the following meanings:

/path/to/original/content.data p>

/path/to/original/.# content.data p>

If the system shuts down somewhere in the process, when you restart the application, you can scan. # content.data and either present it to the user, like what they entered when the system went down or used some custom magic to decide whether it was “complete”, to decide whether to rename it over content.data.

I don’t know what data you write, so I can’t help you decide what kind of “magic” it is, but if it is an xml file, for example, you could analyze it for correctness, and if you do not get an unexpected end of the file, then you probably have the full file.

FWIW, limiting itself to 8k recording, will not save you, because now you are depending on the implementation details in the base OS and FS, which may change in the next version or be different in the previous version.

References:

+1
source

All Articles