Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows: Overwrite File In Use

I am trying to write a utility that will allow moving files in Windows, and when it finds a file in use, will set that file to be moved on reboot.

It seems that MoveFileEx (http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx) is the right call for this, however I cannot figure out what error code I'm looking for from GetLastError (http://msdn.microsoft.com/en-us/library/ms679360(VS.85).aspx) to see that the file was in use.

I want the utility to fail when there is an actual permissions problem. Is there anyway to differentiate a you-can't-write-there and a in-use overwrite error?

Also, if I have the files I am moving in the user's temporary folder, will they get deleted before the delayed rename?

like image 400
singpolyma Avatar asked Apr 02 '09 14:04

singpolyma


People also ask

How do I overwrite a file in Windows?

Right-click the document file the content of which you want to replace. Press the Alt key and select Operations > Replace with File... from the menu bar. Locate and select the file that you want to use for replacing the original file content. Click OK.

How do I stop a file from overwriting?

Select the Components tab and right-click on the component name. Select Details; the Component Details dialog appears. Mark the checkbox option to "Never overwrite if keypath exists." In addition, make sure that the file is the keypath of the Component in the File Key Path field.

How do I overwrite an existing file?

Save As -> Replace File If you are accustomed to selecting "File -> Save As" when saving documents, you can also overwrite the file with your changes this way. Select "Replace File. This is the same behavior as File Save." The original file will be overwritten.


1 Answers

You have to call CreateFile first to see if the file is in use.

To see if the file is in use:

If you get a valid file handle then you know the file does not have conflicting sharing permissions with a process that already has this file open.

If you specify no sharing access (0 to the dwShareMode parameter of the CreateFile call), then you will not get a file handle if any other process is currently using that file in any way. GetLastError in this case would return: ERROR_SHARING_VIOLATION (32)


To see if there is a security problem with accessing the file:

To see if there is a permissions problem accessing that file, the CreateFile call will also fail but with a different GetLastError. You will get: ERROR_ACCESS_DENIED (5)

like image 129
Brian R. Bondy Avatar answered Oct 27 '22 06:10

Brian R. Bondy