14
votes

The Windows API function CreateFile function allows you to specific the desired access. There are three options read, write and delete. If you get a handle from CreateFile requesting Delete access how do you then delete the file using the returned handle? The DeleteFile function takes the file name, not the handle.

Big Picture: When saving files from my application I write out to a temporary file first, then delete the "real" file and rename the temporary file to the real name. I have started to see problems with search indexers, or anti virus/spyware opening the file for reading but not allowing deletes. This causes my save to fail when moving the files around. I have changed my open code to request delete access to make sure I can delete the file when it comes time to save.

This all works fine but I still have a gap where a third party application could grab my file. Since I have an open handle to both the temporary and real files I was looking for a way to perform the delete and rename functions using those handles. The only option I can find is to close the handles and then call the DeleteFile and MoveFile functions. Actually I am currently using the ReplaceFile API function to perform those steps, but it too has file names passed in and will not work unless I close my handles first.

I still need to support XP and cannot start using the new transaction file functions. Is there any way to keep the files locked and still delete/rename them?

1

1 Answers

11
votes

In Windows Vista there is that function SetFileInformationByHandle, that can do what you need.

In previous versions of Windows there is no such function, but you have the equivalent native, not quite public function NtSetInformationFile.

I have no experience with these functions, nor a Windows machine to test them, so I cannot show you the code, but that should not be so difficult.

The general disclaimer about native Windows functions apply, of course.