简体   繁体   中英

Allow User to Delete File In Use By My Application?

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?

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 dwShareMode passed to CreateFile() . This is a bitfield of what you would like to permit another process to do. The bit you are looking for is FILE_SHARE_DELETE which 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 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE 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 FileShare enumeration which you can pass when opening a file, eg. in File.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.

If you call a Delete() or Rename() method onto the Control that is using the file, you can remove it from the PictureBox before it deletes or renames the file.

There shouldn't be much of an issue with doing multiples. With a Checkbox on the Control, you just check each Control to see if that property is true, then call the appropriate method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM