I have an application that reads a linked list1 from a file when it starts, and write it back to the file when it ends. I choose truncate as the file mode when writing back. However, truncate sounds a little bit dangerous to me as it clears the whole content first. Thus if something goes wrong, I cannot get my old stuff back. Is there any better alternative?
1: I use a linked list because the order of items may change. Thus I later use truncate to update the whole file.
The right answer reputation goes to Hans as he first pointed out File.Replace(), though it is not available for Silverlight for now.
This is covered well by the .NET framework. Use the File.Replace() method. It securely replaces the content of your original file with the content of another file, leaving the original in tact if there’s any problem with the file system. It is a better mouse trap than the upvoted answers, they’ll fail when there’s a pending delete on the original file.
There’s an overload that lets you control whether the original file is preserved as a backup file. It is best if you let the function create the backup, it significantly increases the odds that the function will succeed when another process has a lock on your file, the most typical failure mode. They’ll get to keep the lock on the backup file. The method also works best when you create the intermediate file on the same drive as the original so you’ll want to avoid GetTempFileName(). A good way to generate a filename is Guid.NewGuid().ToString().