OrElse
OrElse

Reputation: 9959

Deleting image files within a directory (That might be used by another process)

How can i delete image files (ex *.gif) that might be in use, by another process in a directory?

Upvotes: 1

Views: 670

Answers (3)

CsTamas
CsTamas

Reputation: 4153

You can't delete it, while another process is using it. This comes from low-level file handling of Windows. However you can play around with renaming the file or setting it to be deleted on next boot.

Process Explorer tool can help you finding which process is using the file and it can actually close the handle - given proper/administrative rights. So it is possible with API calls, but such forced close of file handle can result in unpredictable behavior of that process.

Upvotes: 1

BlueMonkMN
BlueMonkMN

Reputation: 25601

If you use My.Computer.FileSystem.DeleteFile, you can notify the user of what program has the file locked if another program is using the file. It can't be deleted if it's in use.

Try
   My.Computer.FileSystem.DeleteFile("C:\Documents and Settings\anybody\Desktop\dummy.doc", _
                                     FileIO.UIOption.AllDialogs, _
                                     FileIO.RecycleOption.DeletePermanently, _
                                     FileIO.UICancelOption.ThrowException)
Catch ex As System.IO.IOException
   Console.WriteLine(ex.ToString())
End Try

Upvotes: 0

David
David

Reputation: 2174

If you can't delete it, you might be able to rename it, but I'm not sure why some locked files can be renamed while others can't.

You can also schedule it to be deleted at next boot using MoveFileEx with a null destination and the MOVEFILE_DELAY_UNTIL_REBOOT flag:
http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx
http://www.pinvoke.net/default.aspx/kernel32/MoveFileEx.html
http://www.pinvoke.net/default.aspx/Enums/MoveFileFlags.html

Upvotes: 0

Related Questions