I think its dangerous to delete the file and rewrite it in place.  Its safer to write to a temporary file in the target directory, and rename the temporary file over to the real name.  If the rename fails (e.g. due to Windows stupidity), you can try deleting the target and then renaming.

IIRC C git takes this approach to file writing.  It almost always writes to a temporary file in the same directory and then tries to rename over to the target.  That way if you crash while writing, the user isn't left with a half-written file that might somehow be taken as an edit.  Instead they are left with a file that isn't updated at all.