Can I allow a user to delete a file, under Windows, that is in use by my application?
In my scenario I have a “quick add” directory that is monitored by my application. When it sees a new image show up it creates a new slide to display in an automated slide show. I would also like to allow my users to delete (and/or rename) a file from my “quick add” directory, and remove it from the slide show.
Is there a way I can flag the file that notifies Windows that I’m okay for it to remove the file while my application is using it?
Yes. In Win32 this is
dwShareModepassed toCreateFile(). This is a bitfield of what you would like to permit another process to do. The bit you are looking for isFILE_SHARE_DELETEwhich allows a delete or a rename while open. However, for the most polite behavior I would recommend including all 3,FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE.[1]Since you’re asking about C# and not Win32, in the .NET world these are included in the
FileShareenumeration which you can pass when opening a file, eg. inFile.Open.Note that these flags don’t let you allow a rename of a file’s parent directory while it is opened by name. That will fail regardless of sharing due to limitations in the kernel (technically in ntfs.sys IIRC).
Footnote
1: Editorial comment: It is a shame that passing
0(which many people do without thinking) happens to be the least permissive option, or that more people writing code on Windows don’t realize what this parameter does and pass these three flags.