ReplaceFile alternative when application keeps file locked

后端 未结 2 1876
名媛妹妹
名媛妹妹 2021-01-12 17:31

Editor FooEdit (let\'s call it) uses ReplaceFile() when saving to ensure that the save operation is effectively atomic, and that if anything goes wrong then the original fil

相关标签:
2条回答
  • 2021-01-12 18:04

    Actually I think there might be a solution that doesn't involve transactions (although transactions are still available as far as I know). I haven't tried it myself, but I think on NTFS it should be possible to create a new file stream (use a long random name to ensure there are no collisions), write your data, and then rename that stream to the stream you actually wanted to write to.

    FILE_RENAME_INFORMATION suggests this should be possible, since it talks about renaming data streams.

    However, this would only work on NTFS. For other file systems I don't think you have a choice.

    0 讨论(0)
  • 2021-01-12 18:10

    I'd like to know what is the simplest way to resolve this race.

    There is no simple way to resolve this race. It's an inherent part of the file system which is not transactional. MS introduced a transactional file API with Vista but now strongly advise developers not to use it as it may be removed in a future release.

    I have had some experience with ReplaceFile but I think it caused more trouble than it was worth. My recollection was that whilst meta data was preserved, a new file was created. A consequence of this was very annoying behaviour for files saved on the desktop. Because such files have their position preserved, creating a new file resulted in the default position being used. So you'd save a file, you'd drag it to the place on the desktop where you wanted to keep it, and then when you saved the file again, it moved back to the default position.

    0 讨论(0)
提交回复
热议问题